Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save bitmap to location

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.

like image 946
Chrispix Avatar asked Mar 16 '09 03:03

Chrispix


People also ask

How do I save a bitmap database?

If you have Bitmap image then you can do following. Bitmap photo = <Your image> ByteArrayOutputStream bos = new ByteArrayOutputStream(); photo. compress(Bitmap. CompressFormat.


2 Answers

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(); } 
like image 142
Ulrich Scheller Avatar answered Oct 01 '22 20:10

Ulrich Scheller


You should use the Bitmap.compress() method to save a Bitmap as a file. It will compress (if the format used allows it) your picture and push it into an OutputStream.

Here is an example of a Bitmap instance obtained through getImageBitmap(myurl) that can be compressed as a JPEG with a compression rate of 85% :

// Assume block needs to be inside a Try/Catch block. String path = Environment.getExternalStorageDirectory().toString(); OutputStream fOut = null; Integer counter = 0; File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten. fOut = new FileOutputStream(file);  Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate fOut.flush(); // Not really required fOut.close(); // do not forget to close the stream  MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName()); 
like image 43
JoaquinG Avatar answered Oct 01 '22 19:10

JoaquinG