【发布时间】:2018-03-03 04:02:19
【问题描述】:
我在 android 中是新的,我有一个应用程序,它使用 Uri 显示来自画廊的图像,并使用位图显示图像,但有时图像加载缓慢并且如果我滚动应用程序挂起虽然我使用通过位图转换 Uri 的标准作为关注:
public static Bitmap getBitmapFromUri(Uri uri ,Context context,ImageView imageView) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = context.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e(LOG_TAG, "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
如下调用该方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Receive the request code if match the product request id start get the image Uri
if (PICK_PRODUCT_IMAGE == requestCode) {
if (data != null) {
imageUri = data.getData();
getContentResolver().takePersistableUriPermission(imageUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
/**
* Start Set The Image Bitmap By Uri Of the Image
* Using {@link UploadImageBitmap#convertImageUriByBitmap(Uri, Context)} }
*/
// productImageView.setImageBitmap(UploadImageBitmap.getBitmapFromUri(imageUri, getApplicationContext(),productImageView));
productImageView.setImageBitmap(UploadImageBitmap.convertImageUriByBitmap(imageUri, this));
}
}
super.onActivityResult(requestCode, resultCode, data);
}
使用它存储 Uri 并显示图像是否比将图像存储在数据库中并直接显示它慢,或者我使用错误的方式显示来自画廊或文件夹的图像?有没有更好的方法来显示画廊和数据库中的图像并具有更好的性能?
【问题讨论】: