简体   繁体   English

将2D数组转换为Java中的图像?

[英]Convert 2D array to Image in Java?

i have 2D array( it's only 1 -0 values) but its type is int[][]. 我有2D数组(只有1 -0值),但是它的类型是int [] []。

Now i want to convert that array into image ( binary image black and white). 现在我想将该数组转换为图像(黑白二进制图像)。 But i couldn't find suitable answer for my question. 但是我找不到适合我问题的答案。 I have searched google and this website. 我已经搜索了谷歌和这个网站。 Can anyone help me?? 谁能帮我??

I have tried this following code, but it 我已经尝试了以下代码,但是

   String path = "C:\\Users\\Cyrus\\Desktop\\test.jpg";
    BufferedImage image = new BufferedImage(b.length, b[0].length, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < b.length; x++) { // b is my 2D array
        for (int y = 0; y < b[x].length; y++) {
            image.setRGB(x, y, b[x][y]);
        }
    }

    File ImageFile = new File(path);
    try {
        ImageIO.write(image, "jpg", ImageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }

// after i modify my code //修改代码后

String path = "C:\\Users\\Cyrus\\Desktop\\test.jpg";
    BufferedImage image = new BufferedImage(a.length, a[0].length, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < a.length; x++) {
        for (int y = 0; y < a[x].length; y++) {
             int value ;
             if(a[x][y]==1)  value = new Color(255,255,255).getRGB();
             else value = new Color(0,0,0).getRGB();
            image.setRGB(x, y, value);

        }
    }

    File ImageFile = new File(path);
    try {
        ImageIO.write(image, "jpg", ImageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }

But it return wrong image 但是返回错误的图像

Can you be more specific on the result you get? 您能否具体说明获得的结果? Did it throw some exceptions? 它引发了一些异常吗? or the program finished normally but didn't produce the result you want? 还是程序正常完成但没有产生您想要的结果?

You should notice that here you want to work with binary image, then is there any specific reason to choose JPG? 您应该注意到,这里要使用二进制图像,那么选择JPG有什么特殊的原因吗? As I know, JPG is not a native representation of color triplet RGB (as bmp for example). 据我所知,JPG不是三元组RGB的本机表示形式(例如bmp)。 a jpeg file is a "container" of data sequence, in which there are a lot of information in its header (EXIF, QT,...), marked by markers. jpeg文件是数据序列的“容器”,其中文件头(EXIF,QT,...)中包含大量信息,并用标记进行标记。 To deal with pixel value "directly" as in your array, the data sequence in jpg file must be "decoded", then after you play it the image, the main image data will be "encoded" again to be jpg stream. 为了像处理数组中的“像素值”那样直接处理jpg文件中的数据序列,必须对其进行“解码”,然后在播放图像后,将主图像数据再次“编码”为jpg流。

To play directly with pixel value, I suggest you work with other formats (such as TGA, png,...) 要直接使用像素值,建议您使用其他格式(例如TGA,png,...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM