英文:
How to force an image to be loaded as ALPHA_8 bitmap on Android with BitmapFactory or ImageDecoder?
问题
我的目标是将 GL_ALPHA 纹理上传到 GPU 并在 OpenGL 中使用它。为此,我需要一个 ALPHA_8 格式的位图。
目前,我正在使用 BitmapFactory 加载一个 8 位(带灰度调色板)的 PNG,但 getConfig() 表示它是 ARGB_8888 格式。
英文:
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.
答案1
得分: 0
我最终使用了PNGJ库,如下:
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;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论