Android从图库中获取图像到ImageView
我试图添加一个从Galery照片到一个ImageView
但我得到这个错误:
java.lang.RuntimeException:将结果ResultInfo {who = null,request = 1,result = -1,data = Intent {dat = content:// media / external / images / media / 1}}传递给activity {hotMetter。 pack / hotMetter.pack.GetPhoto}:java.lang.NullPointerException
这是我的代码:
Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); } Bitmap bitmap=null; public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); tv.setText(selectedImagePath); img.setImageURI(selectedImageUri); } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor == null) return null; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String s=cursor.getString(column_index); cursor.close(); return s; }
我得到了selectedImagePath="mnt/sdcard/DCIM/myimage"
但在img.setImageURI(selectedImageUri);
我得到错误。
我也使用了一个Bitmap
并尝试从SetImageBitmap
设置图像,但我得到了同样的错误。
logcat的:
05-06 19:41:34.191: E/AndroidRuntime(8466): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/externalhttp://img.dovov.commedia/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.access$2000(ActivityThread.java:117) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Handler.dispatchMessage(Handler.java:99) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Looper.loop(Looper.java:123) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invokeNative(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invoke(Method.java:507) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 05-06 19:41:34.191: E/AndroidRuntime(8466): at dalvik.system.NativeStart.main(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): Caused by: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at hotMetter.pack.GetPhoto.onActivityResult(GetPhoto.java:55) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.Activity.dispatchActivityResult(Activity.java:3908) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)
请教。谢谢!
以debugging模式运行应用程序,并在if (requestCode == SELECT_PICTURE)
上设置断点,并在逐步执行时检查每个variables,以确保按预期方式设置断点。 如果您在img.setImageURI(selectedImageUri);
上获得NPE img.setImageURI(selectedImageUri);
那么img
或selectedImageUri
不会被设置。
简单的传递Intent
第一:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE);
你会得到onActivityResult
图片path:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); } }
完整的源代码在这里
尝试以下操作:
import java.io.FileDescriptor; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class ImageGalleryDemoActivity extends Activity { private static int RESULT_LOAD_IMAGE = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture); buttonLoadImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.imgView); Bitmap bmp = null; try { bmp = getBitmapFromUri(selectedImage); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } imageView.setImageBitmap(bmp); } } private Bitmap getBitmapFromUri(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } }
@ parag的代码很好用。 但是,当加载一些大的图像,你可能会失败。 你应该使用;
imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800));
代替;
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
这是我可以使用的方法。
private Bitmap getScaledBitmap(String picturePath, int width, int height) { BitmapFactory.Options sizeOptions = new BitmapFactory.Options(); sizeOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(picturePath, sizeOptions); int inSampleSize = calculateInSampleSize(sizeOptions, width, height); sizeOptions.inJustDecodeBounds = false; sizeOptions.inSampleSize = inSampleSize; return BitmapFactory.decodeFile(picturePath, sizeOptions); } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
这是从画廊和屁股很好地获取图像的最简单的方法
第1步:结果的StartActivity
imageUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("scale", true); intent.putExtra("outputX", 256); intent.putExtra("outputY", 256); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("return-data", true); startActivityForResult(intent, 1); } });
第2步:处理结果
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } if (requestCode == 1) { final Bundle extras = data.getExtras(); if (extras != null) { //Get image Bitmap ProfilePic = extras.getParcelable("data"); imageUser.setImageBitmap(ProfilePic); TextView t=(TextView)findViewById(R.id.textoverimage); t.setText("image Selected"); } } }
我想最简单的方法就是使用库的ContentManager。 这个库用于从设备库,云或照相机获取照片或video。 使用来自云的asynchronous负载以及修复了某些问题设备的错误。
通过Gradle下载: compile 'com.github.stfalcon:contentmanager:0.4.3'
你可以在https://github.com/stfalcon-studio/ContentManagerfind文档;
我认为你的ImageView img没有被实例化,它等于null给编译器; 这就是为什么会引发NullPointerException
你打电话给你的活动吗?
img = (ImageView) findViewById(R.id.my_imageview);
my_imageview是您的ImageView小部件的ID!
原来的答案是你的path必须join像Uri.parse(“file://”+ file.getPath)的前缀;
这是代码,它为我工作。
Button buttonLoadImage = (Button) findViewById(R.id.button4); buttonLoadImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("scale", true); intent.putExtra("outputX", 256); intent.putExtra("outputY", 256); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("return-data", true); startActivityForResult(intent, 1);}}); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { if (requestCode == RESULT_LOAD_IMAGE && data != null) { Uri imageUri = data.getData(); imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageURI(imageUri);}}}
在Manifest文件中添加
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在button点击事件中放置下面的代码
Intent ImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //implicit intent UploadImage.this.startActivityForResult(ImageIntent,99);
将下面的代码放在startActivityforResult事件中
Uri ImagePathAndName = data.getData(); imgpicture.setImageURI(ImagePathAndName);
@Parag Chauhan soltution运行良好,但我有问题 – 一些文件pipe理器应用程序返回Intent对象“file:/// …”而不是“content:// …” – 这是需要使用查询。
这个问题有我的简短解决scheme:
public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { if("content".equals(contentUri.getScheme())) { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else{ return contentUri.getPath(); } } finally { if (cursor != null) { cursor.close(); } } }
基于@Parag解决scheme,
部分解决scheme(@nobre) Android:从内容URI获取文件的URI?
这里的解决scheme(@Nikolay) 从mediastore的URI获取文件名和path
parag-chauhan和devrim的答案是完美的,但我改变onActivityResult没有光标,它使代码更好。
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) { Uri selectedImage = data.getData(); try { ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(getScaledBitmap(selectedImage,800,800)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } private Bitmap getScaledBitmap(Uri selectedImage, int width, int height) throws FileNotFoundException { BitmapFactory.Options sizeOptions = new BitmapFactory.Options(); sizeOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions); int inSampleSize = calculateInSampleSize(sizeOptions, width, height); sizeOptions.inJustDecodeBounds = false; sizeOptions.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions); } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested one final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }