java pixel data_Write pixel data in a grayscale image in java

问题

I am developing a project on image processing where I have to fill the digitized images of cracked paintings. I have to convert a color image to grayscale, performing some calculations on the 2D Array of the gray image and writing it back as gray image. The code for this is:

BufferedImage colorImage=ImageIO.read(new File(strImagePath));

BufferedImage image = new BufferedImage(colorImage.getWidth(),colorImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);

Graphics g = image.getGraphics();

g.drawImage(colorImage, 0, 0, null);

g.dispose();

ImageIO.write(image,"PNG",new File("Image.PNG"));

BufferedImage imgOriginal=ImageIO.read(new File("Image.PNG"));

int width=image.getWidth();

int height=image.getHeight();

BufferedImage im=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);

int arrOriginal[][]=new int[height][width];

for(int i=0;i

for(int j=0;j

arrOriginal[i][j]=imgOriginal.getRGB(j,i)& 0xFF;

for(int i=0;i

for(int j=0;j

im.setRGB(j,i,arrOriginal[i][j]);

ImageIO.write(im,"PNG",new File("Image1.PNG"));

But the output image is very much darker, I am not getting the original image back (I have not done any changes yet).

I think there should be some changes in setRGB() statement but I don't know what.

To write image back, I have also tried:

`

BufferedImage im = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);

WritableRaster raster = im.getRaster();

for(int i=0;i

for(int j=0;j

raster.setSample(j,i,0,arrOriginal[i][j]);

`

But it also don't give me original image back.

Can anyone provide me the solution of this problem?

Thanks in advance.

回答1:

I don't know anything about Java-based image processing, but I do know quite a lot about image processing in general, so I will see if I can give you any ideas. Please don't shoot me if I am wrong - I am just suggesting an idea.

In a greyscale image, the red, green and blue values are all the same, i.e. Red=Green=Blue. So, when you call getRGB and do the AND with 0xff, you are probably getting the blue component only, but that is ok as the red and green are the same - because it's greyscale.

I suspect the problem is that when you write it back to create your new output image, you are only setting the blue component and not the red and green - which should still be the same. Try writing back

original pixel + (original pixel << 8 ) + (original pixel <<16)

so that you set not only the Blue, but also the Red and Green components.

来源:https://stackoverflow.com/questions/20244942/write-pixel-data-in-a-grayscale-image-in-java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值