Android拍照和获取相册图片
之前遇到各种拍照啊,获取相册图片之类,都是直接去度娘,要么之前的代码复制下,没好好总结过。 
再也不要问度娘了,再也不用一堆博客里找啊找了。。。 
一个一个来,先说调用手机相机拍照(最简单版):
cameraButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,TAKE_PHOTO);
}
});
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==RESULT_OK){
Bundlebundle=data.getExtras();
Bitmapbitmap=(Bitmap)bundle.get("data");
photoImageView.setImageBitmap(bitmap);
}
}
这个方法简单是简单了,但是得到的图片却是缩略图,通常都非常模糊,很多时候并不满足我们的要求,我们需要的是获取拍照所得照片的原图。
而通常想要获取拍照所得原图的方法,我们首先会自定义图片名称,确认图片存储位置,之后根据图片位置Uri,自然可以获得原图Bitmap。代码如 
/**
*自定义图片名,获取照片的file
*/
privateFilecreateImgFile(){
//确定文件名
StringfileName="img_"+newSimpleDateFormat("yyyyMMdd_HHmmss").format(newDate())+".jpg";
//Filedir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//Filedir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//Filedir=Environment.getExternalStorageDirectory();
Filedir;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
dir=Environment.getExternalStorageDirectory();
}else{
dir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
}
FiletempFile=newFile(dir,fileName);
try{
if(tempFile.exists()){
tempFile.delete();
}
tempFile.createNewFile();
}catch(IOExceptione){
e.printStackTrace();
}
//获取文件路径
photoPath=tempFile.getAbsolutePath();
returntempFile;
}
//拍照
cameraButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewview){
//只是加了一个uri作为地址传入
Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
FilephotoFile=createImgFile();
photoUri=Uri.fromFile(photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);
startActivityForResult(intent,TAKE_PHOTO);
}
});
 代码应该非常清楚,我们定义了图片名称,将uri传入,那么我们在onActivityResult中就可以得到这个uri,之后岂不是可以直接根据uri得到bitmap了?例如这样: 
Bitmapbitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),photoUri);
photoImageView.setImageBitmap(bitmap);这样做起来是没错的,可惜通常我们手机的摄像头大多非常高清,拍摄出来的照片如果直接加载到手机内存里面,恐怕就啦啦啦啦啦啦了…… 
那么,我们唯一能想到的,就只有开始压缩图片了: 
/**
*压缩图片
*/
privatevoidsetImageBitmap(){
//获取imageview的宽和高
inttargetWidth=photoImageView.getWidth();
inttargetHeight=photoImageView.getHeight();
//根据图片路径,获取bitmap的宽和高
BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(photoPath,options);
intphotoWidth=options.outWidth;
intphotoHeight=options.outHeight;
//获取缩放比例
intinSampleSize=1;
if(photoWidth>targetWidth||photoHeight>targetHeight){
intwidthRatio=Math.round((float)photoWidth/targetWidth);
intheightRatio=Math.round((float)photoHeight/targetHeight);
inSampleSize=Math.min(widthRatio,heightRatio);
}
//使用现在的options获取Bitmap
options.inSampleSize=inSampleSize;
options.inJustDecodeBounds=false;
Bitmapbitmap=BitmapFactory.decodeFile(photoPath,options);
photoImageView.setImageBitmap(bitmap);
}
以上就是调取相机拍照的全部代码,当然WRITE_EXTERNAL_STORAGE这个权限肯定是要加的。
还有一件经常出现的事,就是可能你拍照之后,照片并没有及时出现在手机相册中,而是需要手机重启之后才会出现。其实我们只需要发送一条广播,就可以将图片添加进手机相册,代码如下: 
//将图片添加进手机相册
privatevoidgalleryAddPic(){
IntentmediaScanIntent=newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(photoUri);
this.sendBroadcast(mediaScanIntent);
}
困难已经过去,相对而言,从相册里选取照片,简直再简单不过,我相信只要看下代码就会懂了,不信你看: 
//从相册获取照片
albumButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewview){
//Intentintent=newIntent(Intent.ACTION_PICK);
Intentintent=newIntent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_PHOTO);
}
});
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==RESULT_OK){
switch(requestCode){
caseTAKE_PHOTO:
setImageBitmap();
galleryAddPic();
break;
casePICK_PHOTO:
//data中自带有返回的uri
photoUri=data.getData();
//获取照片路径
String[]filePathColumn={MediaStore.Audio.Media.DATA};
Cursorcursor=getContentResolver().query(photoUri,filePathColumn,null,null,null);
cursor.moveToFirst();
photoPath=cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
//有了照片路径,之后就是压缩图片,和之前没有什么区别
setImageBitmap();
break;
}
}
}
 很简单吧,我们在onActivityResult()中根据data获取到了所选图片的uri,之后只要一步查询,就可以得到图片路径。而有了照片路径,就没有任何问题了。
整个demo到这里就结束了,接下来的内容可以不必看,demo下载链接:下载地址
自问自答时间:
 问:SD卡是什么?因为在我创建File的时候,目录文件默认使用的是Environment.getExternalStorageDirectory(),而在使用之前是需要检测状态的, 也就是这句Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED),询问SD卡是否正确安装。我用了一部新手机,依旧是正确安装的。
答:手机是有内置sd卡的,所以哪怕我买了新手机,但是依旧可以检测到sd卡的存在。 
一个有意思的回答是说,内置的sd卡类似于电脑硬盘,外界的sd卡类似于移动硬盘,但也不确定是否正确。
问:创建File的时候,几个不同的目录文件分别什么意思?有什么不同?
答:直接看测试结果吧,Environment.getExternalStorageDirectory()的地址:/storage/emulated/0 
Environment.getExternalStoragePublicDirectory()的地址:/storage/emulated/0/Pictures
getExternalFilesDir()的地址:/storage/emulated/0/Android/data/com.example.notificationapp/files/Pictures 
问:从相册选取照片的时候,好像有个两个Intent都可以,有什么区别?
答:Intentintent=newIntent(Intent.ACTION_PICK);
 Intentintent=newIntent(Intent.ACTION_GET_CONTENT); 
这两个确实都可以从相册选取照片,但是具体有什么区别,好吧,我没搞明白。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
