0

I am trying to convert a bitmap to base64 using gzip.

I tried the solution here but I got this error GZIP cannot be resolved or is not a field

My solution below is working but the image is being cut at the bottom

enter image description here

this is my code:

        Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg");
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        GZIPOutputStream gzipOstream=null;
        try {
            gzipOstream=new GZIPOutputStream(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100,  gzipOstream);
        byte[] byteArry=stream.toByteArray();
        String encodedImage = Base64.encodeToString(byteArry,  Base64.NO_WRAP);
        try {
            gzipOstream.close();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } 

could this code make the image lose data or is it something on the server side?

Community
  • 1
  • 1
infinite_loop_
  • 179
  • 1
  • 11

1 Answers1

3

After calling mBitmap.compress(); call gzipOstream.flush(); this guarantees that the output byte stream contains everything. Then your toByteArray(); will get the currently missing data.

Try this:

Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
    GZIPOutputStream gzipOstream = null;
    try {
        gzipOstream = new GZIPOutputStream(stream);
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, gzipOstream);
        gzipOstream.flush();
    } finally {
        gzipOstream.close();
        stream.close();
    }
} catch (IOException e) {
    e.printStackTrace();
    stream = null;
}
if(stream != null) {
    byte[] byteArry=stream.toByteArray();
    String encodedImage = Base64.encodeToString(byteArry, Base64.NO_WRAP);
    // do something with encodedImage
}
Simon
  • 10,932
  • 50
  • 49