1

Currently, when I want to save a bitmap to disk I use:

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

Is it possible to have the data written to a byte array instead? I need to manipulate the data that goes to disk and not just the bitmap's image data. The jpg consist of additional stuff like metadata. I don't really care that it's a jpg. I'm not interested in what the data is but just to access the entire data that would normally get written to disk.

Johann
  • 27,536
  • 39
  • 165
  • 279

4 Answers4

2

You can do it using:

public byte[] convertBitmapToByteArray(Bitmap bitmap) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(bitmap.getWidth() * bitmap.getHeight());
    bitmap.compress(CompressFormat.PNG, 100, buffer);
    return buffer.toByteArray();
}
Nermeen
  • 15,883
  • 5
  • 59
  • 72
  • That is wrong. You are creating an array the size of the image. The data written to disk contains, as mentioned, metadata and all the other stuff that goes into a jpg. Remove the sizing and it will work. – Johann Feb 07 '13 at 13:31
2

If you wish to preserve the original pixel data (without compression), you can try this:

public byte[] bitmapToByteArray(Bitmap bitmap) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
    bitmap.copyPixelsToBuffer(byteBuffer);
    return byteBuffer.array();
}
Dheeraj Vepakomma
  • 26,870
  • 17
  • 81
  • 104
2

you can use this code :

      ByteArrayOutputStream out = new ByteArrayOutputStream();

                bMap.compress(Bitmap.CompressFormat.PNG, 100, out);
                byte[] imageArray = out.toByteArray();
Shiv
  • 4,569
  • 4
  • 25
  • 39
-1
U can try this.

if (Utility.isWifiPresent()
                    || Utility.isMobileConnectionPresent()) {
                URL url = new URL(fileUrl);
                InputStream iStream = url.openConnection().getInputStream();// .read(data)
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                byte[] tmpArray = new byte[1024];
                int nRead;
                while ((nRead = iStream.read(tmpArray, 0, tmpArray.length)) != -1) {
                    buffer.write(tmpArray, 0, nRead);
                }
                buffer.flush();
                data = buffer.toByteArray();
                FileOutputStream fOut = null;
        //path to store

                    fOut = Utility.getFileOutputStreamForCloud(
                            sdcardFolderPath, fileUrl);
                }
                fOut.write(data);
                fOut.flush();
                fOut.close();
Srikanth Roopa
  • 1,782
  • 2
  • 13
  • 19