本文介绍了用Java从2D数组构造图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从2D数组创建图像,我使用BufferImage概念构造Image.但是原始图像与下面显示的图像之间存在差异

I want to create the Image from 2D Array.I used BufferImage concept to construct Image.but there is difference betwwen original Image and constructed Image is displayed by image below

我正在使用以下代码

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**** @作者Pratibha*/

/** * * @author pratibha */

public class ConstructImage{
    int[][] PixelArray;
    public ConstructImage(){
        try{

        BufferedImage bufferimage=ImageIO.read(new File("D:/q.jpg"));
        int height=bufferimage.getHeight();
        int width=bufferimage.getWidth();
        PixelArray=new int[width][height];
        for(int i=0;i<width;i++){
            for(int j=0;j<height;j++){
                PixelArray[i][j]=bufferimage.getRGB(i, j);
            }
        }
        ///////create Image from this PixelArray
        BufferedImage bufferImage2=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

        for(int y=0;y<height;y++){
            for(int x=0;x<width;x++){
                int Pixel=PixelArray[x][y]<<16 | PixelArray[x][y] << 8 | PixelArray[x][y];
                bufferImage2.setRGB(x, y,Pixel);
            }


        }

         File outputfile = new File("D:\\saved.jpg");
            ImageIO.write(bufferImage2, "jpg", outputfile);


        }
        catch(Exception ee){
            ee.printStackTrace();
        }
    }

    public static void main(String args[]){
        ConstructImage c=new ConstructImage();
    }
}

推荐答案

您从 getRGB 获得了 ARGB 值,而 setRGB 接受了 ARGB 值,所以这样做就足够了:

You get a ARGB value from getRGB and the setRGB takes a ARGB value, so doing this is enough:

bufferImage2.setRGB(x, y, PixelArray[x][y]);

来自 BufferedImage.getRGB :

...以及 BufferedImage.setRGB :

...and from the API of BufferedImage.setRGB:


另一方面,我建议您改为绘制图像:


On the other hand I would recommend you do paint the image instead:

Graphics g = bufferImage2.getGraphics();
g.drawImage(g, 0, 0, null);
g.dispose();

那么您就不必担心任何颜色模型等了.

Then you wouldn't need to worry about any color model etc.

这篇关于用Java从2D数组构造图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:09
查看更多