在Android中,如何从SD卡显示图像(任意大小)而不会出现内存不足错误?
是否有必要先将图像放入Media Store?
非常感谢伪代码示例。 如果显示的图像与设备的内存级别一样大,则加分。
答案 0 :(得分:13)
编辑:这个问题实际上已经在Strange out of memory issue while loading an image to a Bitmap object(两个最高投票答案)得到了解答。它也使用inSampleSize
选项,但使用小方法自动获取适当的值。
我原来的回答:
inSampleSize
课程的BitmapFactory.Options
可以解决您的问题(http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize)。它的工作原理是制作一个比原始宽度和高度为1 / inSampleSize
的位图,从而减少内存消耗(inSampleSize
^ 2?)。您应该在使用之前阅读该文档。
示例:
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。
答案 1 :(得分: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();
答案 2 :(得分:2)
例如:
yourImgView.setImageBitmap(BitmapFactory.decodeFile("/sdcard/1.jpg"));
答案 3 :(得分: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());
}