Save bitmap to location

Chrispix picture Chrispix · Mar 16, 2009 · Viewed 506.1k times · Source

I am working on a function to download an image from a web server, display it on the screen, and if the user wishes to keep the image, save it on the SD card in a certain folder. Is there an easy way to take a bitmap and just save it to the SD card in a folder of my choice?

My issue is that I can download the image, display it on screen as a Bitmap. The only way I have been able to find to save an image to a particular folder is to use FileOutputStream, but that requires a byte array. I am not sure how to convert (if this is even the right way) from Bitmap to byte array, so I can use a FileOutputStream to write the data.

The other option I have is to use MediaStore :

MediaStore.Images.Media.insertImage(getContentResolver(), bm,
    barcodeNumber + ".jpg Card Image", barcodeNumber + ".jpg Card Image");

Which works fine to save to SD card, but does not allow you to customize the folder.

Answer

Ulrich Scheller picture Ulrich Scheller · Mar 23, 2009
try (FileOutputStream out = new FileOutputStream(filename)) {
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
    e.printStackTrace();
}