android相机、相册获取图片并压缩显示
打开相机
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAPTURE);
}
resolveActivity 查询是否有符合条件的Activity
getPackageManager 获取手机中已安装apk文件信息
输出的图片有2种情况:
①如果你没有指定Intent里面的Extra参数,它就返回一个序列化(putExtra("data", bitmap))的Bitmap(参照1. 获得拍照的预览图)。
②如果你指定了Intent里面的Extra参数MediaStore.EXTRA_OUTPUT,拍照后它就直接把bitmap写到了Uri里面了,返回是空
1. 获得拍照的预览图
使用范围:获得很小的预览图,用于设置头像等地方。
返回:缩略图
public final static int SMALL_CAPTURE = 0;
private Button btn;
private ImageView smallimg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smallimg = (ImageView) findViewById(R.id.small_img);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, SMALL_CAPTURE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SMALL_CAPTURE && resultCode == RESULT_OK) {
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
smallimg.setImageBitmap(imageBitmap);
}
}
}
2. 获得原始的拍照文件
使用范围:用于处理大的图片,比如使用滤镜,上传原始图像等操作,注意Uri不要用data私有目录,否则相机是写不进去的。
返回:Uri
public final static int BIG_CAPTURE = 1;
private Uri outputFileUri;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn2 = (Button) findViewById(R.id.btn_2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = FileUtils.createImageFile();
outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, BIG_CAPTURE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode== BIG_CAPTURE){
Log.i("qqliLog", "outputFileUri: " + outputFileUri);
}
}
文件创建,写到SD卡根目录,(data目录Context.getXXDir()是私有目录,其它程序是写不进去的)
public class FileUtils { public static File createImageFile() {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
try {
File imageFile = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
Environment.getExternalStorageDirectory() /* directory */);
return imageFile;
} catch (IOException e) {
//do noting
return null;
}
}
}
③获取Gallery里面的图片
用途:获取MINETYPE为"image/*"的图片
返回:Uri
public final static int REQUEST_IMAGE = 2;
private Button btn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn3 = (Button) findViewById(R.id.btn_3);
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_IMAGE) {
Log.i("qqliLog", "GalleryUri: " + data.getData());
}
}
通过Uri获取Bitmap对象Uri
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outputFileUri);
img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
但是android4.4以后,返回的URI各种各样很奇怪。。
其实是因为android4.4以后返回的URI只有图片编号,而不是真实的路径
我在网上找了一个亲测没问题的获取图片真实路径的方法:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
但是!!!!
你的图片返回原图的话,,对内存消耗太大,,很容易OOM,,看下图就知道了,,
1.png
本人亲测。。第一个圈是拍摄小图返回缩略图,,第二个圈是拍摄大图返回原图,第三个是读取相机中的图片。。。。很恐怖吧!!!(其实,最早的时候,这是不被允许的,,因为内存太小了,,你懂得,,现在基本上可以,谁手机没个1G啊)
所以,,图片一定要压缩,,
找了很久,,终于找到了一个大牛写的压缩图片方法,,并且不失真哟~~~
/**
* 计算图片的缩放值
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 根据路径获得突破并压缩返回bitmap用于显示
*
* @param filePath
* @return
*/
public static Bitmap getSmallBitmap(String filePath,int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //只返回图片的大小信息
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
不过地址我掉了。。掉了。。你们自己搜去吧。。。
使用就很简单了
img.setImageBitmap(PictureUtil
.getSmallBitmap(getRealPathFromURI(outputFileUri), 480, 800));
好了,,这样就做完了
测试结果:
内存使用情况你看!!!
5.png最后附上项目地址:
https://github.com/QianqianLis/GetScreen
参考:
超完整!Android获取图片的三种方法
http://www.jianshu.com/p/d4793d32a5fb