简体   繁体   English

使用ViewPager处理图像时出现outOfmemomery错误

[英]Using ViewPager, outOfmemomery error when dealing with images

I have been using viewPager to load images: it workers perfectly for two images, however when I increases the number of images it crashed. 我一直在使用viewPager加载图像:它完美地适用于两个图像,但是当我增加崩溃的图像数量时,它却可以正常工作。 I have compressed the image sizes but this did not solve the problem. 我已经压缩了图像大小,但是并不能解决问题。 According to some questions which are similar on StackOverflow I have also used Recycle but this as well did not solve the problem 根据一些在StackOverflow上类似的问题,我也使用了Recycle,但这也不能解决问题。

any other way to increase memory management ? 还有其他增加内存管理的方法吗?

thanks 谢谢

Have you used the sample size to scale them? 您是否使用样本量来缩放它们? Try creating the bitmaps with this, so it loads only the size bitmap required rather than the full size into memory. 尝试以此创建位图,以便它仅将所需大小的位图加载,而不是将完整大小加载到内存中。

public int calculateInSampleSize(BitmapFactory.Options options) {
    DisplayMetrics displayMetrics = cxt.getResources().getDisplayMetrics();
    int reqWidth = displayMetrics.widthPixels;

    final int height = options.outHeight;
    final int width = options.outWidth;

    double devCal2 =  (height*1000)/width;
    int reqHeight = (int) ((devCal2/1000)*reqWidth);

    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

public Bitmap createBitmap(){

    BitmapFactory.Options options2 = new BitmapFactory.Options();
    options2.inJustDecodeBounds = true;
    options2.inDither=true;
    BitmapFactory.decodeFile(cxt.getExternalFilesDir(filepath) +"/companylogo.png",options2);
    options2.inSampleSize = calculateInSampleSize(options2);//=32
    options2.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(cxt.getExternalFilesDir(filepath) +"/companylogo.png",options2);
}

For reference please check http://developer.android.com/training/displaying-bitmaps/load-bitmap.html 作为参考,请检查http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

I also read that using weak reference is a good idea for images, maybe this will help http://eclipsesource.com/blogs/2012/07/31/loading-caching-and-displaying-images-in-android-part-1/ 我还读到使用弱引用是图像的好主意,也许这会有所帮助http://eclipsesource.com/blogs/2012/07/31/loading-caching-and-displaying-images-in-android-part- 1 /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM