Android,Java,创建保持宽高比的缩略图
我正在尝试创建一定高度的缩略图,但保持纵横比。我正在使用下面的代码,但如果图像有点小,生成的图像将不会填充缩略图区域,就会出现问题。 imageURI 只是图像的路径。
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageURI, o);
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=4;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bitmap = BitmapFactory.decodeFile(imageURI, o2);
I'm trying to create a thumbnail of a certain height but maintain the aspect ratio. I'm using the code below but the problem arises when say if an image is somewhat small the image generated will not fill the thumbnail area. imageURI is just the path to the image.
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageURI, o);
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=4;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bitmap = BitmapFactory.decodeFile(imageURI, o2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码始终将位图缩放到至少 1/4 的宽度或高度。如果原始图像已经足够大,它会更小。
我假设您在 ImageView 中显示图像(您的缩略图区域?)。如果图像没有填充 ImageView,您必须配置 ImageView 以正确调整图像大小。如果您的 ImageView 和要显示的图像具有不同的宽高比,则唯一的使图像填充 ImageView 的方法会扭曲图像
我所做的:我使用 BitmapFactory 将图像解码为更大的尺寸,但最好使用 2 的幂作为尺寸。缩放参数,所以我这样做,然后我设置 ImageView 的 android:scaleType 参数以使图像显示为我喜欢的:
Your code is always scaling the bitmap to have at least 1/4 of width or heigth. If the original image is already large enough it will be even smaller.
I assume you display the image in an ImageView (your thumbnail area?. If the image does not fill the ImageView you have to configure the ImageView to resize the image correctly. If your ImageView and the image to display have different aspect ratios, the only way to make the image fill the ImageView will distort the image.
What I do: I use the BitmapFactory to decode the image into a size thats larger, but nearly the size I want the thumbnail to have. Its better to use powers of two as scaling parameter, so I do that. And then I set the android:scaleType parameter of ImageView to make the image display as I like: