开发者社区> 问答> 正文

java中数组和图片的相互转换问题

由于需求,我把一个灰度图片转成了一个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再转成图片格式呢?

展开
收起
蛮大人123 2016-03-13 14:43:13 2567 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    试试这个呢,不是用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();
            }
    2019-07-17 19:02:35
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载