0

我想将 4mb、19mb、3mb 大小的图像从 sd 卡加载到图像视图中。

BitmapFactory.Options options=new BitmapFactory.Options();
 options.inJustDecodeBounds=true;
 InputStream inputStream=new BufferedInputStream(new FileInputStream(fileName));
 options.inSampleSize=2;
 options.inJustDecodeBounds=false;
 Bitmap bmp=BitmapFactory.decodeFile(fileName,options);

当我使用此代码时,我无法获得所有图像的确切尺寸。根据屏幕功能,应加载图像。如果屏幕能够加载 19mb 图像,我不想使用 option.insampleSize=2。如果它没有那个,那一次我只想为那个 18Mb 和其他我不想那样做的图像减小图像的大小。

4

2 回答 2

0

你可以做这样的事情

int sampleSize = 1;

while (true) {
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = sampleSize;
        options.inJustDecodeBounds = false;

        InputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
        Bitmap bmp=BitmapFactory.decodeFile(fileName,options);

        // some code here

        break;
    } catch (OutOfMemoryError oom) {
        sampleSize++;
    }
}
于 2013-01-05T09:59:08.130 回答
0

您可以动态请求屏幕大小

int screenSize = (resources.getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK);
DisplayMetrics metrics = resources.getDisplayMetrics();

然后使用

metrics.widthPixels, metrics.heightPixels 

或者

if (screenSize == Configuration.SCREENLAYOUT_SIZE_SMALL) // or another constant screen sizes in Configuration class.

并请求图像大小而不使用图像的 URI 加载整个图像:

InputStream input = contentResolver.openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
int originalHeight = onlyBoundsOptions.outHeight; 
int originalWidth = onlyBoundsOptions.outWidth;

然后在运行时选择 inSampleSize。

于 2013-01-05T10:00:27.470 回答