Reputation: 75
I am trying to upload a image to google drive using API. I ve searched so much but i didn't find a way. I ve got a demo code which uploads a text file and it works. i need to change it to upload image. This is the code...
public void CreateFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
@Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello abhay!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("abhaytest2")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
How can i change this code to upload a image from file.(by given location of the image in device).? I ve found few tutorials but those are deprecated methods.
Upvotes: 0
Views: 2481
Reputation: 417
Use this code to upload image to google drive...
new Thread() {
@Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
// Write the bitmap data from it.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(title)
.build();
Bitmap image = BitmapFactory.decodeFile(location));
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i("E", "Unable to write file contents.");
}
image.recycle();
outputStream = null;
String title = "noisy";
Log.i("E", "Creating new pic on Drive (" + title + ")");
Drive.DriveApi.getFolder(mGoogleApiClient,driveId)
.createFile(mGoogleApiClient, metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
Upvotes: 1