7

在 Android 中,如何显示SD 卡中的图像(任意大小),而不会出现内存不足错误

是否需要先将图像放入媒体商店?

一个伪代码示例将不胜感激。如果显示的图像与设备的内存级别一样大,则加分

4

4 回答 4

13

编辑:这个问题实际上已经在Strange out of memory issue 中得到了回答,同时将图像加载到 Bitmap 对象(两个最高投票的答案)。它也使用该inSampleSize选项,但使用一种小方法来自动获取适当的值。

我原来的答案:

该类可以解决您的问题(inSampleSizehttp://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize 。它的工作原理是制作一个位图,其宽度和高度比原来的高 1/,从而减少内存消耗(通过^2?)。您应该在使用它之前阅读文档。BitmapFactory.OptionsinSampleSizeinSampleSize

例子:

BitmapFactory.Options options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 8;

// don't ever use a path to /sdcard like this, but I'm sure you have a sane way to do that
// in this case nebulae.jpg is a 19MB 8000x3874px image
final Bitmap b = BitmapFactory.decodeFile("/sdcard/nebulae.jpg", options);

final ImageView iv = (ImageView)findViewById(R.id.image_id);
iv.setImageBitmap(b);
Log.d("ExampleImage", "decoded bitmap dimensions:" + b.getWidth() + "x" + b.getHeight()); // 1000x485

但是,在这里它仅适用于最大为inSampleSize允许内存大小的 ^2 倍的图像,并且会降低小图像的质量。诀窍是找到合适的 inSampleSize。

于 2010-12-19T14:13:58.630 回答
4

我正在使用代码显示任何大小的图像:

ImageView imageView=new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
FileInputStream fis=new FileInputStream(file);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
options.inPurgeable=true; //if necessary purge pixels into disk
options.inScaled=true; //scale down image to actual device density
Bitmap bm=BitmapFactory.decodeStream(is, null, options);
imageView.setImageBitmap(bm);
fis.close();
于 2010-12-20T19:28:32.280 回答
2

例如:

yourImgView.setImageBitmap(BitmapFactory.decodeFile("/sdcard/1.jpg"));
于 2010-12-17T15:26:36.253 回答
0

http://www.developer.com/ws/other/article.php/3748281/Working-with-Images-in-Googles-Android.htm涵盖了您需要了解的有关图像主题的所有信息,包括获取它们来自 SD 卡。您会注意到执行此操作的代码,复制如下:

try {
   FileOutputStream fos = super.openFileOutput("output.jpg",
      MODE_WORLD_READABLE);

   mBitmap.compress(CompressFormat.JPEG, 75, fos);

   fos.flush();
   fos.close();
   } catch (Exception e) {
   Log.e("MyLog", e.toString());
}
于 2010-12-17T13:12:44.153 回答