Android. Obtaining image size from it's resource id

流过昼夜 提交于 2019-12-18 01:53:41

问题


This is a part of my Activity:

private ImageView mImageView;
private int resource;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  resource = getIntent().getIntExtra("res", -1);

  Matrix initMatrix = new Matrix();

  mImageView = new ImageView(getApplicationContext());
  mImageView.setScaleType( ImageView.ScaleType.MATRIX );
  mImageView.setImageMatrix( initMatrix );
  mImageView.setBackgroundColor(0);
  mImageView.setImageResource(resource);
}

I try to display an image within an ImageView using a matrix as scale type (I want to add multitouch later). But before user starts interaction i want the image to be centered and fit inside the ImageView. I already found answers concerning how to solve it but there is one problem for me: to make image centered using matrix I need to know its width and height. Is there any way of getting image size when all you have is int resource ?


回答1:


Use BitmapFactory.decodeResource to obtain a Bitmap object of the resource, and then from the bitmap you can easily retrieve the image width/height with getHeight and getWidth

Also do not forget to recycle your bitmap

EDIT:

This way you will get a null bitmap as output, but the BitmapFactory.Options will be set with the with and height for the bitmap. So, in this case,, you do not need to recycle the bitmap

BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
dimensions.inJustDecodeBounds = true;
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap, dimensions);
int height = dimensions.outHeight;
int width =  dimensions.outWidth;



回答2:


For anyone that didn't read dmon's comment. The code to do this looks like this:

final Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.your_photo, opt);

opt.outHeight; // height of resource
opt.outWidth; // width of resource


来源:https://stackoverflow.com/questions/9655534/android-obtaining-image-size-from-its-resource-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!