android中的灰度位图

ric*_*dtz 3 android image bitmap image-processing grayscale

我有一个对应于“灰度位图”(一个字节-> 一个像素)的字节数组,我需要为此图像创建一个 PNG 文件。

下面的方法有效,但创建的 png 很大,因为我使用的位图是 ARGB_8888 位图,每个像素需要 4 个字节而不是 1 个字节。

我无法让它与 ARGB_8888 不同的其他 Bitmap.Config 一起工作。也许 ALPHA_8 是我需要的,但我一直无法让它工作。

我也尝试过其他一些帖子中包含的 toGrayScale 方法(在 Android 中将位图转换为灰度),但我对大小有同样的问题。

public static boolean createPNGFromGrayScaledBytes(ByteBuffer grayBytes, int width,
        int height,File pngFile) throws IOException{

    if (grayBytes.remaining()!=width*height){
        Logger.error(Tag, "Unexpected error: size mismatch [remaining:"+grayBytes.remaining()+"][width:"+width+"][height:"+height+"]", null);
        return false;
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    // for each byte, I set it in three color channels.
    int gray,color;
    int x=0,y=0;        
    while(grayBytes.remaining()>0){

        gray = grayBytes.get();
        // integer may be negative as byte is signed. make them positive. 
        if (gray<0){gray+=256;}

        // for each byte, I set it in three color channels.
        color= Color.argb(-1, gray, gray, gray);


        bitmap.setPixel(x, y, color);
        x++;
        if (x==width){
            x=0;
            y++;
        }           
    }
    FileOutputStream fos=null;

    fos = new FileOutputStream(pngFile);
    boolean result= bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
    fos.close();
    return result;
}       
Run Code Online (Sandbox Code Playgroud)

编辑:链接到生成的文件(它可能看起来无意义,但只是用随机数据创建的)。 http://www.tempfiles.net/download/201208/256402/huge_png.html

任何帮助将不胜感激。

Err*_*454 5

正如您所注意到的,将灰度图像保存为 RGB 非常昂贵。如果您有亮度数据,那么最好保存为灰度 PNG 而不是 RGB PNG。

Android 框架中可用的位图和图像功能真正适用于读取和写入框架和 UI 组件支持的图像格式。此处不包括灰度 PNG。

如果您想在 Android 上保存灰度 PNG,则需要使用像http://code.google.com/p/pngj/这样的库

  • 更改为使用您建议的库,并且效果很好。非常感谢! (2认同)