【问题标题】:Android - How to efficiently change Bitmap dimensionsAndroid - 如何有效地更改位图尺寸
【发布时间】:2013-08-18 17:23:12
【问题描述】:

我有一个 android 应用程序,我在其中加载资源图像文件并为它们创建纹理,以便我可以使用 OpenGL 渲染它们。但是,我使用的是 mipmap,并且图像尺寸必须是 2 的幂。这就是为什么我可能需要在制作纹理之前增加给定位图的宽度或高度。

这是我目前完成工作的代码:

    Bitmap bitmap = BitmapFactory.decodeResource(this.context.getResources(), resourceId);

    Bitmap newBitmap = Bitmap.createBitmap(nextPowerOfTwo(bitmap.getWidth()), 
            nextPowerOfTwo(bitmap.getHeight()), bitmap.getConfig());

    int x=0,y=0,width=bitmap.getWidth(),height=bitmap.getHeight();
    int [] pixels = new int[width * height];
    bitmap.getPixels(pixels, 0, width, x, y, width, height);
    newBitmap.setPixels(pixels, 0, width, x, y, width, height);
    bitmap.recycle();
    gl.glGenTextures(1, textures, textureCount);
            ...

这在我的 Asus TF101 和 Nexus 4 上运行良好,但我在以下行中遇到了 Galaxy S3(可能还有更多设备)的 OutOfMemory 异常:

int [] pixels = new int[width * height];

通过阅读,我意识到对 Bitmap.createBitmap 的调用也很耗费内存,我正在尝试想办法减少内存浪费。 想到的第一个想法是使用较小的 2D 数组作为“int[] 像素”并一次复制更少的像素。但我想知道是否还有其他更有效的方法可以做到这一点。

【问题讨论】:

    标签: android exception memory opengl-es bitmap


    【解决方案1】:

    因为你只是创建一个缩放位图,这个方法应该可以解决你的问题: http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap, int, int, boolean)

    Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, nextPowerOfTwo(bitmap.getWidth()), nextPowerOfTwo(bitmap.getHeight()), false);
    bitmap.recycle();
    

    【讨论】:

    • 这不是最好的解决方案,因为位图缩放(在这种情况下放大)会损害其质量。这就是为什么我现在只是简单地向位图添加空白空间,然后给 openGL 具有我的原始图像的纹理坐标,并且像素保持在它们的位置。其他构造函数只能创建位图的子集。还有其他解决方案吗?
    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多