由于需求,我把一个灰度图片转成了一个short类型的数组。
File file = new File("grayImage.jpg");
BufferedImage src=ImageIO.read(file);
int width=src.getWidth(null);
int height=src.getHeight(null);
int minX=src.getMinX();
int minY=src.getMinY();
short[] rgb = new short[3];
short[] grayImage=new short[width*height];
for(int i=minX;i<height;i++){
for(int j=minY;j<width;j++){
//System.out.print(bi.getRGB(jw, ih));
int pixel=src.getRGB(j, i);
rgb[0] = (short) ((pixel & 0xff0000 ) >> 16) ;
rgb[1] = (short) ((pixel & 0xff00 ) >> 8) ;
rgb[2] = (short) (pixel & 0xff );
grayImage[i*width+j]=(short)(rgb[0] * 0.299 + rgb[1] * 0.587 + rgb[2] * 0.114);
}
}
现在我对的到的grayImage操作完了,并对像素值做了一些修改,那我应该如何
把short[] grayImage再转成图片格式呢?
试试这个呢,不是用short数组,用的int数组,输出的是灰度图片。
int[] data1 = new int[grayImage.length];
for (int i = 0; i < data1.length; i++) {
data1[i] = new Color(grayImage[i],grayImage[i],grayImage[i]).getRGB();
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
image.setRGB(minX, minY, width, height, data1, 0, width);
String path = "D:\\test.png";
try {
ImageIO.write(image, "png", new File(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}```
把灰度转为彩色?不可能的吧.把彩色转为灰度应该属于有损压缩,恢复不回去的了.
只是要转成图片格式的话,把RGB都设成灰度的数值就可以了