0

A subproblem in my app is that I have to post an image to a server, where it is further processed. I am currently sending images by encoding them (jpeg compressed) into a base64 string, and then posting as json. However, this led to erroneous results. On debugging, I realized that the base64 representation of image formed by android was incorrect. (I tested this by comparing with the base64 representation of the image made by the base64 utility in linux) .

My code to get a base64 representation of an image is as follows

// get base64 encoded image from bitmap
public String getEncodedImage(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

I am passing a bitmap to the above function, which is obtained as

final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

Can someone suggest a reason why this code might lead to an incorrect base64 representation for some images?

Thanks in advance.

quantumcoder
  • 33
  • 1
  • 1
  • 7

1 Answers1

0

If you already have it in the file, there is no reason to decompress it then recompress it- which may be the cause of your errors, as each compression is lossy and will lead to further loss of data. If you already have an image file, read it in as raw bytes and Base64 that.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127