java 在 Android 中裁剪和调整图像大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4579499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:02:28  来源:igfitidea点击:

Crop and resize an image in Android

javaandroidimagebitmap

提问by smith324

I am reading an image from disk and displaying it inside of a row in a ListView. The image files are larger than what needs to be displayed inside the ImageViewof the rows. Since I need to cache the bitmapsin RAM for faster access I would like them to only be as large as the ImageViews (85x85 dip)

我正在从磁盘读取图像并将其显示在ListView. 图像文件比需要ImageView在行内显示的文件大。由于我需要bitmaps在 RAM 中缓存以加快访问速度,因此我希望它们仅与ImageViews一样大(85x85 dip)

Right now I am reading in the file with

现在我正在阅读文件

bitmap = BitmapFactory.decodeFile(file);

位图 = BitmapFactory.decodeFile(file);

and the ImageView is responsible for scaling and cropping it

ImageView 负责缩放和裁剪它

android:scaleType="centerCrop"

android:scaleType="centerCrop"

AFAIK this is keeping the entire bitmap in memory (because I cached it XD) and that is bad

AFAIK 这将整个位图保存在内存中(因为我缓存了它 XD),这很糟糕

How can I remove this responsibility from the ImageView and do the crop + scale while loading the file? All the bitmaps will be displayed at 85x85 dip and need to be 'centerCrop'

如何从 ImageView 中删除此责任并在加载文件时进行裁剪 + 缩放?所有位图将以 85x85 倾斜显示,并且需要为“centerCrop”

回答by Phyrum Tea

You can find out the dimensions of your pictures before loading, cropping and scaling:

您可以在加载、裁剪和缩放之前找出图片的尺寸:


BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    Bitmap bmo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

Then load it in sample size:

然后以样本大小加载它:


...
options.inSampleSize = 1/2;
bmo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

...
 = Bitmap.createScaledBitmap(bmo, dW, dH, false);

don't forget to recycle temporary bitmaps or you'll get OOME.

不要忘记回收临时位图,否则你会得到 OOME。


bmo.recycle();