Search code examples
androidandroid-cameraandroid-bitmapbitmapfactoryimage-compression

When I'm compressing the image size getting from gallary, the height and width are also compressed


My problem is when I am compressing the image size (Mb to Kb) that I'm getting from the gallery, the height and width of the image are also compressing. Can anyone tell me how I can resolve this problem? I want to get the image in full size (full height and full width).

This is the code of onclick listener on the image:

 try {
  IsProfilePic = 5;
  usrimage5.setImageBitmap(Bitmap.createScaledBitmap(selectedBitmap, usrimage5.getWidth(), usrimage5.getHeight(), false));
  usrimage5.setScaleType(ImageView.ScaleType.FIT_XY);
  if (usrimage5.getTag() != new Integer(0))
  DeleteImageID = usrimage5.getTag().toString();
 } catch (OutOfMemoryError e) {
  Log.e("Nithin 5", "" + e.toString());
 }

and this is the code with which I am compressing the image:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded = resizeBase64Image(Base64.encodeToString(byteArray, Base64.DEFAULT));

This is the method resizeBase64Image() that I am calling when I am resizing the image:

 public String resizeBase64Image(String base64image) {
    byte[] encodeByte = Base64.decode(base64image.getBytes(), Base64.DEFAULT);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPurgeable = true;
    Bitmap image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length, options);

    if (image.getHeight() <= 400 && image.getWidth() <= 400) {
        return base64image;
    }
    image = Bitmap.createScaledBitmap(image, 400, 400, false);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG, 100, baos);

    byte[] b = baos.toByteArray();
    System.gc();
    return Base64.encodeToString(b, Base64.NO_WRAP);
}

Solution

  • selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    

    This line will result in compressing your image in MAX quality, which probably isn't your goal. If you want to compress your image to a lower size (and JPEG format), set quality to a lower value (Ex: use 90 or 80 instead of 100)

    image.compress(Bitmap.CompressFormat.PNG, 100, baos);
    

    This line won't compress your image since PNG is a lossless format and will ignore the integer value (Here you have used 100, which is the max value anyway).

    image = Bitmap.createScaledBitmap(image, 400, 400, false);
    

    This is the line which is scaling your image into a lower dimension. You can simply ignore this method in your code and your image won't be resized.

    Follow this link to get some more idea about image compression and scaling.