0

I am using the following code to encode my image bitmap into a byte[] and then to a string but at the time of encoding it into byte[] it says unable to encode..

Bitmap bm = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        (bm).compress(Bitmap.CompressFormat.JPEG, 100, stream);
        bm.recycle();
        byte[] byteFormat = stream.toByteArray();
        String encodedImage = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

The app is working fine, but I am stuck here. Suggest issues.

  • Here , check the accepted answer: http://stackoverflow.com/questions/4830711/how-to-convert-a-image-into-base64-string – resw67 Nov 10 '16 at 08:29
  • `encoding it into byte[]` you are compresing the bitmap to a jpg byte array. After that you base64 encode the bytes to a string. It is unclear about which action/statement you are talking. – greenapps Nov 10 '16 at 08:37
  • @greenapps , What I actually want to do is to store an image as a byte array and then convert it to a string, then I will store that string and when I would want to use the image I will convert that string into byte array and then display the image in some imageview. – Prateek Paliwal Nov 10 '16 at 09:06
  • if you want to "store that string" why not to store `byte[]` or even better use `FileOutputStream` in `compress()` method call? – pskink Nov 10 '16 at 09:09
  • That all can be true. But why did you tell all instead of answer my question? – greenapps Nov 10 '16 at 09:09

2 Answers2

0
public static byte[] bitmapToByteArray(Bitmap bitmap){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    bitmap.recycle();
    return  byteArray;
}
Arsen Sench
  • 440
  • 3
  • 18
0

Try this for me this works :)

public String imageToBaseString(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        Bitmap bm = BitmapFactory.decodeFile(path, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos); 
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
   }
Jeevanandhan
  • 978
  • 8
  • 16