简体   繁体   English

Android位图不会压缩

[英]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. 我正在尝试压缩从用户的画廊或相机拍摄的位图,并将其作为个人资料图片存储在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 :] 谢谢 :]

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 : inSampleSize文档:

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. 如果设置为大于1的值,则请求解码器对原始图像进行二次采样,返回较小的图像以节省内存。 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. 例如,inSampleSize == 4返回的图像为原始宽度/高度的1/4,像素数目的1/16。 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. 任何小于等于1的值都与1相同。注意:解码器使用基于2的幂的最终值,任何其他值将四舍五入为最接近的2的幂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM