2011-12-08 77 views
1

我试图创建一个16位的PNG,但不能让它保持只写黑色。另外我怎么能转换一个8位颜色定义为255,255,255/r,g,b到16位颜色?我如何创建一个16位的灰度图像与java

BufferedImage bi = new BufferedImage(256, 256, 
      BufferedImage.TYPE_USHORT_GRAY); 

    // 65536 
    for (int i = 0; i < 256; i++) 
     for (int j = 0; j < 256; j++) { 
      int mask = 0xf0 
      int value = 255 & mask; // zero other bits 
      value >>= 16; 
      bi.setRGB(i, j, value); 
      // bi.setRGB(i, j, 65536); 
     } 

    File f = new File("gray.png"); 

    try { 
     ImageIO.write(bi, "png", f); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

回答

1

该行value >>= 16将其设置为零。

至于从24位RGB转换为16位颜色,通常有两种方法...... RGB565和RGB555。数字表示给每个颜色分量多少位。

0

不是解决此问题的方法,而是完成要求的另一种方式。

BufferedImage bi = new BufferedImage(256, 256, BufferedImage.TYPE_USHORT_GRAY); 

Graphics2D g = bi.createGraphics(); 
g.setColor(Color.GRAY); 

g.fillRect(0,0,256,256); 
File f = new File("C:/gray.png"); 

try { 
    ImageIO.write(bi, "png", f); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

对不起,我不是由我的电脑,但你能告诉我,是否创建一个8位或16位PNG?谢谢! – user1088777

+0

@ user1088777我不知道。 [Here](http://stackoverflow.com/q/4116858/862441)是一个相关的SO问题,可能有所帮助。 – srkavin