1.从本地相册获取照片:一般就是写出这个方法 protected void getImageFromAlbum() { Intent intent = new Intent(Intent.ACTION_PICK);...
1.从本地相册获取照片:
一般就是写出这个方法
protected void getImageFromAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//相片类型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
2.从照相机获取照片
一般就是写出这个方法
protected void getImageFromCamera() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED))
{
Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
}
else {
Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
}
}
写完这个方法后,一般我们还需要通过响应这个方法去获取图片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_IMAGE)
{
Uri uri = data.getData(); //to do find the path of pic
}
else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA )
{
Uri uri = data.getData(); //to do find the path of pic } }
但是,有时候我们会发现用相机拍摄获取照片的时候,得到的 uri 是 null 的,这是因为android把拍摄的图片封装到bundle中传递回来,但是根据不同的机器获得相片的方式不太一样,可能有的相机能够通过
inten.getData()获取到uri
然后再根据uri获取数据的路径,在封装成bitmap,但有时候有的相机获取到的是null的,这时候我们该怎么办呢?
其实这时候我们就应该从bundle中获取数据,通过
(Bitmap) bundle.get("data")
获取到相机图片的bitmap数据。
为了能够同时适应上述两种情况,我们这时候就应该在获取图片时做判断了。我们可以在响应的时候做一个判断:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE_PICK_IMAGE) {
Uri uri = data.getData(); //to do find the path of pic by uri
}
else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA )
{ Uri uri = data.getData();
if(uri == null){ //use bundle to get data
Bundle bundle = data.getExtras();
if (bundle != null) {
Bitmap photo = (Bitmap) bundle.get("data"); //get bitmap //spath :生成图片取个名字和路径包含类型
saveImage(Bitmap photo, String spath);
}
else
{
Toast.makeText(getApplicationContext(), "err****", Toast.LENGTH_LONG).show(); return;
}
}
else
{
//to do find the path of pic by uri
}
}
}
后面的过程就需要通过bitmap转化成相应的图片文件了。不过得到最终 的图片是被压缩了的。
public static void saveImage(Bitmap photo, String spath) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(spath, false));
photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
这样就能解决照相机取到的图片uri为空的状态了。但是在获取到uri为null情况下,如果想得到没有被压缩过的照片,也就是说得到的是直接从相机拍摄到的照片怎么做呢?