android中如何获取拍照后的缩略图和和原图
详细很多android开发人员都会遇到这样的问题,但是,往往都是当时解决了,并没有总结,下次遇到同样的问题仍然要花很多时间去搞,下面是 我总结的一点点经验:
- 1 获取拍照后的缩略图
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
- 2 结果
系统会发缩略图放在data里面;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {//获取缩率图
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImage.setImageBitmap(imageBitmap);
}
- 3 原图
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
System.out.println("ImageActivity.onClick");
}
// Continue only if the File was successfully created
if (photoFile != null) {
//设置存放图片的file
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 111);
}
}
//获取存放img的file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
if (storageDir.exists()) {
System.out.println("ImageActivity.createImageFile");
}
File images = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
// mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return images;
}
4 结果
if (requestCode == 111) {
Glide.with(this).load(photoFile).into(mImage);
}
这里的photoFile就是上面的createImageFile方法生成的;
//将一个file图片添加到相册,上面的方法拍的照片并不会存在相册里面,凡是有uri的地方都要注意,因为7.0后要哟过fileprovider.
private void galleryAddPic(File f) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
5 需要权限
-6 note
注意在调用startActivityForResult()方法之前,先调用resolveActivity(),这个方法会返回能处理该Intent的第一个Activity(译注:即检查有没有能处理这个Intent的Activity)。执行这个检查非常重要,因为如果在调用startActivityForResult()时,没有应用能处理你的Intent,应用将会崩溃。所以只要返回结果不为null,使用该Intent就是安全的。