繁体   English   中英

如何将位图压缩为较小尺寸的图像(保持宽高比)

[英]how to compress a bitmap to a lower size image (keeping aspect ratio)

我只是想压缩位图,以便获得较小尺寸的图像。 像2mb图像到-100kb,但保持图像的长宽比。

我已经在网上尝试了一些代码,但有时无法正常工作,甚至在压缩后获得更大的图像尺寸。 那么我该怎么做呢? 但无论如何,我在网上找到了以下代码:

private Bitmap getBitmap(int path, Canvas canvas) {

    Resources resource = null;
    try {
        final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
        resource = getResources();

        // Decode image size
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resource, path, options);

        int scale = 1;
        while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
                IMAGE_MAX_SIZE) {
            scale++;
        }
        Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight);

        Bitmap pic = null;
        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            options = new BitmapFactory.Options();
            options.inSampleSize = scale;
            pic = BitmapFactory.decodeResource(resource, path, options);

            // resize to desired dimensions
            int height = canvas.getHeight();
            int width = canvas.getWidth();
            Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height);

            double y = Math.sqrt(IMAGE_MAX_SIZE
                    / (((double) width) / height));
            double x = (y / height) * width;

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true);
            pic.recycle();
            pic = scaledBitmap;

            System.gc();
        } else {
            pic = BitmapFactory.decodeResource(resource, path);
        }

        Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight());
        return pic;
    } catch (Exception e) {
        Log.e("TAG", e.getMessage(),e);
        return null;
    }
}

我有图像路径,但我不知道什么是canvas(第二个参数)。 还有没有更好的方法来压缩位图? 谢谢

您可能需要查看此Android Developers帖子。 另外,要从路径解码位图,请使用BitmapFactory.decodeFile()

暂无
暂无

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

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