Bitmap的getWidth和getHeight方法获取到的尺寸与实际尺寸不符的问题

将一张原始大小为2155*1233的图片放在drawable-xhdpi中,运行在模拟器上。该模拟器的相关参数如下:

getResources().getDisplayMetrics().density:2.625
getResources().getDisplayMetrics().densityDpi:420
getResources().getDisplayMetrics().scaledDensity:2.625

在代码中通过一下代码获取该图片的宽高:

mOption = new BitmapFactory.Options();
mOption.inJustDecodeBounds = false;
mBitmap = BitmapFactory.decodeResource(getResources(),mResId,mOption)
Log.i(TAG,"测试图片的宽高 mBitmap.getWidth():"+mBitmap.getWidth()+"  mBitmap.getHeight():"+mBitmap.getHeight());

打印得到测试图片的宽高 mBitmap.getWidth():2828 mBitmap.getHeight():1592

原因:
android的分辨率与对应的文件夹得关系如下:

drawable文件夹dpimdpihdpixhdpixxhdpixxxhdpi
分辨率120160240320480640

将图片放在drawble-xhdpi文件夹中,而此时模拟器得实际分辨率是420,因此对齐进行了相应得缩放:2155 * 1233变成了【2155 *(420/320)】 * 【1233 *(420/320)】,长宽都进行了相应得缩放。
备注:如果图片放得文件夹与当前手机的分辨率是完全对应的,则不会对其进行缩放。

由上可以知道,当图片所在的文件夹与手机分辨率不一致时,通过Bitmap.getWidth()和Bitmap.getHeight()得到的宽高是对图片进行缩放后的宽高。那么我们要如何得到图片的原始尺寸呢?
方法1:可以获取图片的原始宽高,但是获取的Bitmap对象是null
通过Option.outWidth和Option.outHeight属性获取。Option类中的属性注释如下:

/**
* The resulting width of the bitmap. If {@link #inJustDecodeBounds} is
* set to false, this will be width of the output bitmap after any
* scaling is applied. If true, it will be the width of the input image
* without any accounting for scaling.
*
* <p>outWidth will be set to -1 if there is an error trying to decode.</p>
*/
public int outWidth;

/**
* The resulting height of the bitmap. If {@link #inJustDecodeBounds} is
* set to false, this will be height of the output bitmap after any
* scaling is applied. If true, it will be the height of the input image
* without any accounting for scaling.
*
* <p>outHeight will be set to -1 if there is an error trying to decode.</p>
*/
public int outHeight;

当inJustDecodeBounds设置为true时得到的是不会经过缩放的图片原始长宽,设置为false时是scale(对应的属性为inSampleSize)后的长宽,如果scale是1则得到的也是原始长宽。

一般情况下我们都是将inJustDecodeBounds设置为true读取图片的宽高,注意此时得到的Bitmap对象是null的。

方法2:如果想拿到图片的原始尺寸,也想拿到获取对应的Bitmap,可以通过下列方式

BitmapFactory.Options mOptions = new BitmapFactory.Options();
mOptions.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, mOptions);
if (bitmap != null) {
   Log.i(TAG, "bitmap width: "+bitmap.getWidth()+", bitmap height: "+bitmap.getHeight());
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值