Simone Sessa
Simone Sessa

Reputation: 873

Convert OutputStream (to File) to Bitmap

With Google Drive Rest Api I've tried to download ad image, using this.

I get a list of file with this code:

List<String> fileInfo = new ArrayList<>();
FileList result = mService.files().list()
        .setPageSize(10)
        .setQ("mimeType='image/jpeg'")
        .setFields("nextPageToken, files(id, name)")
        .execute();
        List<File> files = result.getFiles();
        if (files != null) {
            for (File file : files) {
                fileInfo.add(String.format("%s (%s)\n",
                        file.getName(), file.getId()));
            }
        }

And it works. Then, with the file id, I obtain an OutputStream with this code:

String fileId = "file_id";
OutputStream fOut = new ByteArrayOutputStream();
mService.files().export(fileId,"image/jpeg").executeMediaAndDownloadTo(fOut);

Now, how can I convert it into a file and then into a bitmap?

Upvotes: 2

Views: 5417

Answers (2)

kaay
kaay

Reputation: 1093

Old question, but still relevant... maybe this wasn't possible back then, but nowadays this should do:

try (InputStream is = mService.files().get(fileId).executeMediaAsInputStream()) {
    return BitmapFactory.decodeStream(is);
}

Upvotes: 1

Brijesh Kumar
Brijesh Kumar

Reputation: 1685

You can try this. byte[] bitmapdata = fOut.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Upvotes: 8

Related Questions