如何在Android中减小JPEG图像的大小

问题描述 投票:7回答:3

在我的应用程序中,我正在调用相机应用程序并拍照并将其保存在特定目录(例如/ sdcard等)中

图片被保存为JPEG图像。如何缩小图像尺寸?是否有可用的图像编码器或压缩方式?

我在以下位置看到了另一篇文章:Android Reduce Size Of Camera Picture

但是这是缩放图像。我正在寻找可以压缩或编码的东西。有可能吗?

感谢,秘鲁语

android image encoding compression jpeg
3个回答
13
投票

我不确定无论如何您都可以尝试一下。要减小图像的大小,首先应将图像转换为位图,然后再将其保存到特定目录,然后压缩位图以设置图像的质量并将其写入正确的路径。可以更改图像的质量,希望这将有助于您减小图像的尺寸。

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);` 

API

compress (Bitmap.CompressFormat format, int quality, OutputStream stream)

1
投票

可能下面的代码对您有用

        opt = new BitmapFactory.Options();
        opt.inTempStorage = new byte[16 * 1024];
        opt.inSampleSize = 4;
        opt.outWidth = 640;
        opt.outHeight = 480;
        Bitmap imageBitmap = BitmapFactory
                .decodeStream(in, new Rect(), opt);
        Bitmap map = Bitmap.createScaledBitmap(imageBitmap, 100, 100, true);
        BitmapDrawable bmd = new BitmapDrawable(map);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        map.compress(Bitmap.CompressFormat.PNG, 90, bao);
        ba = bao.toByteArray();
        imagedata=Base64.encodeBytes(ba);

0
投票

使用受本文启发的Glide

https://developer.android.com/topic/performance/graphics/load-bitmap

Gilde API

https://bumptech.github.io/glide/

// using some options for JPEG
RequestOptions myOptions = new RequestOptions()
                        .encodeFormat(Bitmap.CompressFormat.JPEG)
                        .override(1280, 1024) // this is what you need to take care of WxH
                        .fitCenter(); // or centerCrop
// uri may be local or web url anything
Glide.with(this).asBitmap().load(uri).apply(myOptions).listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        showSnackBar("There was some error in fetching images");
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap bitmap, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        // do whatever with the bitmap object here
                        return true;
                    }
                }).submit();
© www.soinside.com 2019 - 2024. All rights reserved.