java.lang.OutOfMemoryError:位图大小超过VM预算

时间:2011-08-08 15:23:03

标签: android

我正在使用BitmapFactory从文件解码JPG,然后使用imageBitmap设置ImageView。有时,该应用程序崩溃为“java.lang.OutOfMemoryError: bitmap size exceeds VM budget

我尝试过使用:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(filepath, options);
它似乎工作了一段时间,但现在不再了。我该怎么办?

4 个答案:

答案 0 :(得分:1)

在Android中,可以为应用程序分配多少内存,可能是大约16 MB到32 MB。 (Upto Android版)

对于2百万像素,位图所需的内存为2 * 4 = 8 M.

要减少内存消耗,您需要降低图像分辨率。说WVGA,800x480以

开头

词shash

答案 1 :(得分:0)

减少使用的图像数量或缓存它们,如果缓存它们,请将它们存储在您需要的最小尺寸中。

此致  斯特凡

答案 2 :(得分:0)

这是缓存图像文件的代码。

protected static Map<String, Drawable> cacheThumbs = new HashMap<String, Drawable>();

//缓存图片的代码

                if( thumbUri.length() == 0 )
                    return;
                Drawable d = cacheThumbs.get( thumbUri );
                if( d == null )
                {
                    String fileName = movie.getId()+"_"+thumbUri.substring( thumbUri.lastIndexOf('/')+1 );
                    cacheFile = new File( application.getCacheDir(), fileName );
                    if( !cacheFile.exists() )
                    {
                        //Log.v(LOG_TAG,"Fetching "+thumbUri +" and caching in "+cacheFile.getAbsolutePath() );
                        InputStream bis = (InputStream) new URL(thumbUri).getContent();
                        BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( cacheFile ) );
                        int read = 0;
                        while( (read = bis.read( buffer )) != -1 )
                            bos.write( buffer, 0, read );
                        bis.close();
                        bos.close();                         
                        Log.v(LOG_TAG,thumbUri + " fetched");
                    }//if
                    Log.v(LOG_TAG,thumbUri + " in cache");
                    BufferedInputStream bis = new BufferedInputStream( new FileInputStream( cacheFile ), 9000 );
                    d = Drawable.createFromStream( bis, "src name");
                    bis.close();
                    cacheThumbs.put( thumbUri, d );

此致  斯特凡

答案 3 :(得分:0)

我想为此讨论添加不同的观点。我确实阅读了很多线程和建议,最后用WebView显示单个图像。对于单个图像而言,它不适用于画廊。它的工作完美,可以通过选项进行缩放,可滚动,最后没有内存错误; - )

适用于从网络加载的图像以及本地图像。这是一个小例子:

WebView webView = (WebView) findViewById(R.id.your_webview);

String html = "<html><head><title>A title</title></head><body bgcolor=\"#000000\"><img src=\"" + url + "\"></body></html>";

WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);   
webSettings.setUseWideViewPort(true);

webView.setScrollbarFadingEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.loadDataWithBaseURL("fake://fake.com", html, "text/html", "UTF-8", null);
相关问题