[英]retrieve image from gallery in android
我创建了一个Activity
,其中有一个Button
。
按下按钮会打开一个 android Gallery
。 当我从图库中选择一个图像时,它会在我的Activity
的ImageView
中显示它,但是在第二次选择后出现以下错误
01-13 17:55:25.323: ERROR/AndroidRuntime(14899): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
这是我正在使用的源代码:
public class MyImage extends Activity {
/** Called when the activity is first created. */
Gallery gallery;
private Uri[] mUrls;
String[] mFiles=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File images = Environment.getDataDirectory();
File[] imagelist = images.listFiles();
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
Gallery g = (Gallery) findViewById(R.id.Gallery01);
g.setAdapter(new ImageAdapter(this));
g.setFadingEdgeLength(40);
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(260, 210));
return i;
}
private Context mContext;
}
}
有很多与此相关的答案。 检查一下。
我也遇到过这个完全相同的问题。 为了防止这种情况发生,您可以做的是确保在加载新位图之前回收先前的位图。 调用 Bitmap.recycle() 来做到这一点。 http://developer.android.com/reference/android/graphics/Bitmap.html#recycle ()
我没有看到您在代码中处理位图的位置,但您明白了吗?
处理位图时的另一件事是记住它们在读入内存时实际有多大,并且您是否真的需要为您的用例提供那么大的图像。 如果您不需要完整图像,您可以以较低的采样率将位图读取到您的应用程序中。 这样可以节省大量内存。
这是很常见的问题。 可能是因为你有很多图像,而Android模拟器堆大小很小。 所以每次使用后你都必须回收你的imagebitmap。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.