I save a photo from my application in an array of bitmap. Then when I took the pictures I needed, I call the saveAll() function as shown in the code below.

 public void saveAll(View view) { for (Bitmap b : arrBitmap) { SystemClock.sleep(1000); try { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { return; } FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(convertBitmapToByteArray(b)); fos.close(); Toast.makeText(context, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { } } } private byte[] convertBitmapToByteArray(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(bitmap.getWidth() * bitmap.getHeight()); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); return stream.toByteArray(); } private static File getOutputMediaFile() { File mediaStorageDir = new File("/sdcard/", "JCG Camera"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; } } String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; } 

and the photo is saved very strange, firstly it may not save at all or save everything except the first one or not save at first, but then when I further test the code they may appear ... although every time it shows Toast that everything is saved ... please tell me

what am I doing wrong?

  • Can you show what the Exception e displays? - Saidolim
  • So he does not deduce anything, shows that the function works out completely ... - Aleksey Timoshchenko

1 answer 1

You somehow make it too difficult to save a Bitmap to a file. This is done very simply:

 FileOutputStream out = null; try { 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 (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } 

I think the problems are precisely because of the complexity.
In addition, working with a large number of Bitmap 's you risk catching OOM

  • Your example shows that you do not need to translate back from Bitmap to byte []. And write () is also not necessary? As far as I understand, we create a place for saving, then we create a file which we will save and we must write our bytes to this file? So? - Aleksey Timoshchenko
  • @AlekseyTimoshchenko, a place to write the file is not previously created. Bitmap.compress() will write the image in the selected format and with the selected compression to any OutputStream . В данном случае . В данном случае FileOutputStream` - Vladyslav Matviienko