一、获取图片大小有两张情况代码如下:
package com.jhq.picdemo;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private String path = "/storage/emulated/0/data/mytest/mytest.png"; //图片路径
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission(); //权限检查
}
protected void onResume () {
super.onResume();
getImageSize(); //获取尺寸大小
}
private void getImageSize() {
/*第一种直接把bitmap加载到内存中,通过对bitmap的测量,
得出宽高,由于这个方法直接把图片引入内存,
如果图片过大,将会引发OOM;*/
//方法一:通过uri把图片转化为bitmap的方法
Bitmap bitmap= BitmapFactory.decodeFile(path);//从本地sdcard获取图片,如从其他文件中获取图片,可参考文末的链接。
int height= bitmap.getHeight();
int width= bitmap.getWidth();
Log.i(TAG,"通过bitmap获取到的图片大小" + "width: "+ width+" height: "+ height);
/*bitmap.options类为bitmap的裁剪类,通过他可以实现bitmap的裁剪;
如果不设置裁剪后的宽高和裁剪比例,返回的bitmap对象将为空,
但是这个对象存储了原bitmap的宽高信息。*/
//方法二:使用Options类来获取
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//这个参数设置为true才有效,
Bitmap bmp = BitmapFactory.decodeFile(path, options);//这里的bitmap是个空
if(bmp == null){
Log.e(TAG,"通过options获取到的bitmap为空 ===");
}
int outHeight=options.outHeight;
int outWidth= options.outWidth;
Log.i(TAG,"通过Options获取到的图片大小"+ "width:"+ outWidth +" height: " + outHeight);
}
//sd 卡权限动态申请
private void checkPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "");
}
}
}
}
log打印:
Android读取不同位置(drawable,asset,sdCard)的图片资源
参考地址:https://blog.csdn.net/Jason_996/article/details/48311985