Android 如何使用 BitmapFactory 选项缩放图像
我想使用 BitmapFactory.decodeFile(path, options) 解码 SD 卡中的图像。
我还希望将大于 2048x2048 像素的图像缩小到最多 2048x2048(保持比例)。
我可以在获取位图后手动执行此操作,但这除了已分配的字节之外还需要分配大量字节。
我应该如何设置 BitmapFactory.Options 对象才能获得该效果?
谢谢
I want to decode an image from the SD card with BitmapFactory.decodeFile(path, options).
I also want images that are larger than 2048x2048 pixels to be scaled down to at most 2048x2048 (maintaining the proportions).
I could do this manually after getting the bitmap, but that would require allocating a large amount of bytes in addition to the ones already allocated.
How should i set up my BitmapFactory.Options object to get that effect?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首次加载时使用 BitmapFactory.Options.inSampleSize使图像的大小尽可能接近目标大小,然后使用 Bitmap.createScaledBitmap 缩放到您想要的确切大小。
这个答案中有一些代码。
Use BitmapFactory.Options.inSampleSize when you first load your image to get the size as close as possible to your target size, then use
Bitmap.createScaledBitmap
to scale to the exact size you want.There's some code for this in this answer.
首先在
Options
中将inJustDecodeBounds
设置为true
,这将为您提供图像的大小,而无需加载任何图像数据。< br>如果图像尺寸小于最大尺寸,则照常加载即可。
另一方面,如果它太大,请使用
inSampleSize
读取较小的位图。注意:我认为使用 inSampleSize 时解码不会进行任何过滤,因此您可能会丢失一些细节,但由于您的图像尺寸太大(2048 px),我认为这不会会引起任何问题。
Start by setting
inJustDecodeBounds
totrue
in yourOptions
, this will give you the size of the image, without loading any of the image data.If the image size is smaller then your max size, then just load it as usual.
If on the other hand, it is too big, use the
inSampleSize
to read a smaller bitmap.Note: I don't think that the decoding does any filtering when using the inSampleSize, so you might lose some detail, but as your image size is so big (2048 px) I don't think this will cause any problems.
您可以尝试这样的操作:
在这里您可以添加自己的宽度和高度。
bitmapPicture
是Bitmap
的对象。让我知道这对您是否有帮助。
You can try something like this:
Here you can add your own width and height.
bitmapPicture
is the object ofBitmap
.Let me know if this is of any help to you.