Search code examples
javaandroidopengl-esandroid-bitmap

How to force an image to be loaded as ALPHA_8 bitmap on Android with BitmapFactory or ImageDecoder?


My goal is to upload a GL_ALPHA texture to the GPU and use it with OpenGL. For that, I need a bitmap in ALPHA_8 format.

Currently, I'm using BitmapFactory to load a 8-bit (with grayscale palette) PNG but getConfig() says it's in ARGB_8888 format.


Solution

  • I ended up using the PNGJ library, as follows:

    import ar.com.hjg.pngj.IImageLine;
    import ar.com.hjg.pngj.ImageLineHelper;
    import ar.com.hjg.pngj.PngReader;
    
    public static Bitmap loadAlpha8Bitmap(Context context, String fileName) {
        Bitmap result = null;
    
        try {
            PngReader reader = new PngReader(context.getAssets().open(fileName));
    
            if (reader.imgInfo.channels == 3 && reader.imgInfo.bitDepth == 8) {
                int size = reader.imgInfo.cols * reader.imgInfo.rows;
                ByteBuffer buffer = ByteBuffer.allocate(size);
    
                for (int row = 0; row < reader.imgInfo.rows; row++) {
                    IImageLine line = reader.readRow();
    
                    for (int col = 0; col < reader.imgInfo.cols; col++) {
                        int pixel = ImageLineHelper.getPixelRGB8(line, col);
                        byte gray = (byte)(pixel & 0x000000ff);
                        buffer.put(row * reader.imgInfo.cols + col, gray);
                    }
                }
    
                reader.end();
    
                result = Bitmap.createBitmap(reader.imgInfo.cols, reader.imgInfo.rows, Bitmap.Config.ALPHA_8);
                result.copyPixelsFromBuffer(buffer);
            }
        } catch (IOException e) {}
    
        return result;
    }