setImageBitmap()不工作
问题描述:
我已经和ImageView的,它应该是充满图像从画廊与此代码:setImageBitmap()不工作
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Pick an image.");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);
现在,一切都很好在这部分代码,问题是在onActivityResult()中,完全在setImageBitmap()中,因为imageView没有采用来自Gallery的图像。这是onActivityResult()代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE_REQUEST || resultCode == PromoUpload.RESULT_OK){
Uri selectedImage = data.getData();
String[] filepathColumm = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filepathColumm, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepathColumm[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
imagePromo.setImageBitmap(bitmap);
pictureFlag = 1;
}
我敬酒picturePath
属性和它的显示OK,问题正是在这里:
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
imagePromo.setImageBitmap(bitmap);
但我不知道我在做什么错误。这是ImageView的的XML:
<ImageView
android:id="@+id/imageView_promo"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:padding="1dp" />
我也尝试选择从多个尺寸的图像,但它似乎没有工作...
答
但我不知道我做错了
你假设每个Uri
来自MediaStore
,并且MediaStore
中的每个条目都有一个有用的路径。这两个都不是真的。
什么,你应该做的是通过selectedImage
到的图像加载库(滑翔,毕加索等),因为这些图书馆不仅知道如何正确使用Uri
,但他们会做一个图像加载后台线程,而不是像在这里一样冻结UI。您还可以教导图像加载库来缩放图像以适应您的需求,以节省堆空间。
更直接替换你的代码是:
Uri selectedImage = data.getData();
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
imagePromo.setImageBitmap(bitmap);
pictureFlag = 1;
但是,如上所述,这将会冻结您的UI,同时磁盘I/O和图像解码是怎么回事。
答
会帮这个,
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath,bmOptions);
imageView.setImageBitmap(bitmap);
谢谢!替换帮助。无论如何,正如你所说,我会尝试将Glide或毕加索实施到我的项目中。 –