我有一个应用程序,允许用户转到照片库并选择一张照片用作头像。该代码在任何地方都可以正常工作,但 Xoom 除外,它会启动图库,允许用户选择照片,然后失败并显示“java.lang.RuntimeException:无法解包位图”。我正在使用以下方法调用图库:
public Intent getImagePickerIntent(int width, int height) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("setWallpaper", false);
intent.putExtra("return-data", true);
return intent;
}
然后我使用以下代码获取位图数据:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PHOTO_PICKED) {
// If the activity successfully captured a photo
if(resultCode == Activity.RESULT_OK && data.getExtras() != null) {
// Resize photo to 100x100 and then save to user's device
try {
// putting this in a try-catch after seeing odd exceptions on a Xoom
ImageHelper.save(PrefsActivity.this, MyApplication.DEVICE_PHOTO_FILE_NAME, ImageHelper.resize((Bitmap)data.getExtras().getParcelable("data"), 100, 100));
请注意,我通过调用 (Bitmap)data.getExtras().getParcelable("data")
这在 Android 2.3 及以下版本上运行良好,知道为什么它在 3.x 中失败了吗?
编辑:为了让它更令人兴奋,同样的代码在 Honeycomb 上的常规 Activity 中运行良好。此特定问题发生在 PreferencesActivity 中。
最佳答案
我最近在尝试在 onActivityResult 方法中返回位图时遇到了类似的问题。令人费解的是,以下代码适用于 SDK 3,但无法适用于更高版本:
Bundle extras = intent.getExtras();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("someImage");
作为解决方法,我在使用 startActivityForResult 调用的 Activity 中将位图转换为字节数组:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
intent.putExtra( "myByteArray", stream.toByteArray() );
回到 onActivityResult 后,我通过以下方式检索它:
byte[] myByteArray = intent.getExtras().getByteArray("myByteArray");
然后我使用以下内容转换回位图:
InputStream is = new ByteArrayInputStream(myByteArray);
Bitmap bmp = BitmapFactory.decodeStream(is);
我希望这对某人有帮助。
关于Android 无法解包 Honeycomb 上的位图错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6460889/