压缩图像以满足文件大小限制(Android)

时间:2016-11-21 04:25:20

标签: android image bitmap compression android-bitmap

我已经实现了下面的代码来缩放图像,相对于纵横比(通过按比例减小相对于彼此的高度/宽度)..这肯定有助于减小图像的大小上传到我的后端,但这没有考虑到图像的分辨率。我想设置一个硬图像限制,比如800Kb,如果调整大小后图像大于800Kb,则压缩到小于800Kb的点。

任何人都有这样的经历吗?我很好奇传入Bitmap.Compress方法的质量参数和每个百分比质量削减了多少文件大小之间的关系 - 如果我能获得这些信息,我相信我可以实现我的目标。

感谢您提前获得任何帮助,我目前的代码如下,也许它将有助于其他人在未来朝着这个方向前进。

public static void uploadImage(String url, File file, Callback callback, Context context,
                               IMAGE_PURPOSE purpose) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

    int maxWidth = 0;
    int maxHeight = 0;
    int maxSize = 0;
    switch(purpose){
        case PROFILE:
            maxWidth = Constants.MAX_PROFILE_IMAGE_WIDTH;
            maxHeight = Constants.MAX_PROFILE_IMAGE_HEIGHT;
            maxSize = Constants.MAX_PROFILE_IMAGE_SIZE;
            break;
        case UPLOAD:
            maxWidth = Constants.MAX_UPLOAD_IMAGE_WIDTH;
            maxHeight = Constants.MAX_UPLOAD_IMAGE_HEIGHT;
            maxSize = Constants.MAX_UPLOAD_IMAGE_SIZE;
            break;
    }

    int newWidth = bitmap.getWidth();
    int newHeight = bitmap.getHeight();

    // Make sure the width is OK
    if(bitmap.getWidth() > maxWidth){

        // Find out how much the picture had to shrink to get to our max defined width
        float shrinkCoeff = ((float)(bitmap.getWidth() - maxWidth) / (float)bitmap.getWidth());
        newWidth = maxWidth;

        // Shrink the height by the same amount to maintain aspect ratio
        newHeight = bitmap.getHeight() - (int)((float)bitmap.getHeight() * shrinkCoeff);
    }

    // Make sure the height is OK
    if(newHeight > maxHeight){

        // Find out how much the picture had to shrink to get to our max defined width
        float shrinkCoeff = ((newHeight - maxHeight) / newHeight);
        newHeight = maxHeight;

        // Shrink the width by the same amount to maintain aspect ratio
        newWidth = newWidth - (int)((float)newWidth * shrinkCoeff);
    }

    Bitmap resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

    // Get the image in bytes
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    resized.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    byte[] imageBytes = bos.toByteArray();

    // If the size on disk is too big, reduce the quality
    if(imageBytes.length > maxSize){
        // Compress image here to get to maxSize
    }

0 个答案:

没有答案