由于需求,我把一个灰度图片转成了一个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();
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。