在 Android 上将大的位图文件调整为缩放的输出文件 [英] Resize a large bitmap file to scaled output file on Android
问题描述
我在一个文件中有一个大的位图(比如 3888x2592).现在,我想将该位图的大小调整为 800x533 并将其保存到另一个文件中.我通常会通过调用 Bitmap.createBitmap
方法来缩放位图,但它需要一个源位图作为第一个参数,我无法提供,因为将原始图像加载到 Bitmap 对象中当然会超过内存(例如,请参见此处).
I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file.
I normally would scale the bitmap by calling Bitmap.createBitmap
method but it needs a source bitmap as the first argument, which I can't provide because loading the original image into a Bitmap object would of course exceed the memory (see here, for example).
我也无法读取位图,例如,BitmapFactory.decodeFile(file, options)
,提供一个 BitmapFactory.Options.inSampleSize
,因为我想要将其调整为精确的宽度和高度.使用 inSampleSize
会将位图大小调整为 972x648(如果我使用 inSampleSize=4
)或 778x518(如果我使用 inSampleSize=5
,这是甚至不是 2 的幂).
I also can't read the bitmap with, for example, BitmapFactory.decodeFile(file, options)
, providing a BitmapFactory.Options.inSampleSize
, because I want to resize it to an exact width and height. Using inSampleSize
would resize the bitmap to 972x648 (if I use inSampleSize=4
) or to 778x518 (if I use inSampleSize=5
, which isn't even a power of 2).
我还想避免使用 inSampleSize 读取图像,例如在第一步中使用 972x648,然后在第二步中将其大小调整为 800x533,因为与直接调整原始大小相比,质量会很差图像.
I would also like to avoid reading the image using inSampleSize with, for example, 972x648 in a first step and then resizing it to exactly 800x533 in a second step, because the quality would be poor compared to a direct resizing of the original image.
总结一下我的问题:有没有办法读取 10MP 或更大的大图像文件并将其保存到一个新的图像文件,调整为特定的新宽度和高度,而不会出现 OutOfMemory 异常?
To sum up my question: Is there a way to read a large image file with 10MP or more and save it to a new image file, resized to a specific new width and height, without getting an OutOfMemory exception?
我也尝试过 BitmapFactory.decodeFile(file, options)
并将 Options.outHeight 和 Options.outWidth 值手动设置为 800 和 533,但它不能那样工作.
I also tried BitmapFactory.decodeFile(file, options)
and setting the Options.outHeight and Options.outWidth values manually to 800 and 533, but it doesn't work that way.
推荐答案
不.我希望有人纠正我,但我接受了您尝试的加载/调整大小方法作为妥协.
No. I'd love for someone to correct me, but I accepted the load/resize approach you tried as a compromise.
以下是供任何人浏览的步骤:
Here are the steps for anyone browsing:
- 计算仍能生成大于目标图像的最大可能
inSampleSize
. - 使用
BitmapFactory.decodeFile(file, options)
加载图像,将 inSampleSize 作为选项传递. - 使用
Bitmap.createScaledBitmap()
调整到所需的尺寸.
- Calculate the maximum possible
inSampleSize
that still yields an image larger than your target. - Load the image using
BitmapFactory.decodeFile(file, options)
, passing inSampleSize as an option. - Resize to the desired dimensions using
Bitmap.createScaledBitmap()
.
这篇关于在 Android 上将大的位图文件调整为缩放的输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!