Android上传图片到服务器前减小图片大小

3

我必须将从相机/图库中捕获的图像上传到服务器。在许多应用程序中,我看到分辨率为1000X560的图像大小为35 KB。而在我的情况下,图像大小高达380 KB。我的手机相机拍摄的图像分辨率为2368X4224,大小小于2 MB。如何保持图像的高分辨率同时使其大小低?以下是我迄今为止尝试过的方法:

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(realPath, bmOptions);
bmOptions.inSampleSize = 1;
bmOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmOptions.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(realPath, bmOptions);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

我已经阅读过这篇文档。我面临的问题是如何决定图像的最小宽度和最小高度。


应用比例因子缩小您的图像。 - M D
@MD,我没有理解你的意思。能否请您详细说明一下? - Nitish
1个回答

3

你能否查看http://voidcanvas.com/whatsapp-like-image-compression-in-android/ 这个链接。

我认为这是最好的图像压缩教程。
同时请查看这个回答:https://dev59.com/Tuo6XIcBkEYKwwoYIAgL#26928768
希望这些能有所帮助。

编辑:这里有图片大小调整。

//      max Height and width values of the compressed image is taken as 816x612

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;


 //      width and height values are set maintaining the aspect ratio of the image
        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {               imgRatio = maxHeight / actualHeight;                actualWidth = (int) (imgRatio * actualWidth);               actualHeight = (int) maxHeight;             } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

我已经阅读了这个教程。他们使用的最大宽度和高度为816和612。这就是我不明白的地方。我应该使用硬编码值还是应该进行一些计算,或者这些值是在哪些因素上决定的?实际上,我将在一个电子商务应用程序中使用它。 - Nitish
好的,但这取决于您的图像尺寸要求。对于我的电子商务应用程序,我建议您确定最大宽度和高度,如果图像大于此大小,则可以调整大小。请检查已编辑的答案(“resize”函数)。 - Govinda P
尝试过,但是分辨率降至 457X816,文件大小仍为 276 KB。我必须在保持分辨率高的同时保持文件大小低。 - Nitish
尝试将压缩比从80降低到60,即scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 60, out); - Govinda P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接