Android中获取选择图片与获取拍照返回结果差异

时间:2024-01-02 18:50:44

导语:

如今的安卓应用在选择图片的处理上大多合并使用拍照和从相册中选择这两种方式

今天在写一个这样的功能时遇到一个尴尬的问题,同样是拍照获取图片功能,在不同手机上运行的效果不一样,下面是在某型手机上测试的报错结果

错误报告:

10-21 17:41:43.634: E/AndroidRuntime(32683): FATAL EXCEPTION: main

10-21 17:41:43.634: E/AndroidRuntime(32683): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=-1, data=Intent { act=inline-data (has extras) }} to activity {*****}: java.lang.NullPointerException

问题分析:

这是出错部分代码,可以看到我直接从返回Intent中获取uri,但实际上有些手机在拍照后uri是空的,所以空指针异常也不奇怪了

       if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
if (bmp != null)
bmp.recycle();
bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
bmp = MediaStore.Images.Media.getBitmap(cr, uri);
imagedata = StreamUtils.stream2ByteArray(cr
.openInputStream(uri));
AVFile img_file = new AVFile("photo_1", imagedata);
img_file.saveInBackground();
images.add(img_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
photo.setImageBitmap(bmp);
} else {
Toast.makeText(PublishActivity.this, "请重新选择图片",
Toast.LENGTH_SHORT).show();
}

所以解决方法就是分别处理从相册选取和拍照这两种情况,以便能适应更多的设备

解决办法

10代表拍照,20代表从相册选取。

     if (requestCode == 10) {
    if (resultCode == RESULT_OK) {
if (bmp != null)
bmp.recycle(); bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
imagedata = baos.toByteArray();
AVFile img_file = new AVFile("photo_1", imagedata);
img_file.saveInBackground();
images.add(img_file);
photo.setImageBitmap(bmp);
} else {
Toast.makeText(PublishActivity.this, "请重新选择图片",
Toast.LENGTH_SHORT).show();
}
}
if (requestCode == 20) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
if (bmp != null)
bmp.recycle();
bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
bmp = MediaStore.Images.Media.getBitmap(cr, uri);
imagedata = StreamUtils.stream2ByteArray(cr
.openInputStream(uri));
AVFile img_file = new AVFile("photo_1", imagedata);
img_file.saveInBackground();
images.add(img_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
photo.setImageBitmap(bmp);
} else {
Toast.makeText(PublishActivity.this, "请重新选择图片",
Toast.LENGTH_SHORT).show();
}
}