Aidan Laing
Aidan Laing

Reputation: 1300

Android Bitmap won't compress

I'm trying to compress a Bitmap which is taken from either the user's gallery or camera and store it as a profile picture in a Parse Server.

The issue is the bitmap will NOT compress. The image saves perfectly fine and is useable in the database, but the file size is massive for just a profile picture.

Here's my current code:

//Compressing
ByteArrayOutputStream stream = new ByteArrayOutputStream();
profilePictureBitmap.compress(Bitmap.CompressFormat.PNG, 20, stream);
byte[] image = stream.toByteArray();

//Saving
String imageName = username + "_profile_picture.png";
final ParseFile file = new ParseFile(imageName, image);
file.saveInBackground(new SaveCallback() {
    @Override
    public void done(ParseException e) {
        if(e == null) {
            user.put("profilePicture", file);
            user.signUpInBackground();
        }
    }
}

I'm using a image picker library that gets the path of the image. I then turn it into a bitmap.

Heres my code to retrieve the image:

ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
if(images.size() > 0) {
    Image image = images.get(0);
    File imgFile = new File(image.getPath());
    if(imgFile.exists()){
        profilePictureBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        profilePictureImage.setImageBitmap(profilePictureBitmap);
    }
}

If there is any ideas on how to fix this I would greatly appreciate it. Thanks :]

Upvotes: 1

Views: 1309

Answers (1)

kris larson
kris larson

Reputation: 30985

Image image = images.get(0);
File imgFile = new File(image.getPath());
if(imgFile.exists()){
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 2;  // one quarter of original size
    profilePictureBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), opts);
    profilePictureImage.setImageBitmap(profilePictureBitmap);
}

Docs for inSampleSize:

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

Upvotes: 3

Related Questions