如何在java中将矩阵转换为图像

时间:2015-10-12 19:10:57

标签: java image matrix

我有一个填充1和0的矩阵a [512] [512],我怎么能将这个矩阵转换为图像(.png,.jpg等)。

2 个答案:

答案 0 :(得分:2)

这将从您创建的矩阵中创建灰度图像:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

//Consider class and methods predefined. The following will be within a method

try {
    BufferedImage image;
    for(int i=0; i<yourmatrix.length; i++) {
        for(int j=0; j<yourmatrix[].length; j++) {
            int a = yourmatrix[i][j];
            Color newColor = new Color(a,a,a);
            image.setRGB(j,i,newColor.getRGB());
        }
    }
    File output = new File("GrayScale.jpg");
    ImageIO.write(image, "jpg", output);
}

catch(Exception e) {}

答案 1 :(得分:0)

如果您开始使用整个图像的1D大数组,这是另一种可以避免for循环的方法。

int width = 512;
int height = 512;
byte[][] a = new byte[width][height];

byte raw[] = new byte[width * height];
for (int i = 0; i < a.length; i++) {
    System.arraycopy(a[i], 0, raw, i*width, width);
}
//Arrays.fill(raw, width*height/2, width*height, (byte)1);
byte levels[] = new byte[]{0, -1};
BufferedImage image = new BufferedImage(width, height, 
        BufferedImage.TYPE_BYTE_INDEXED,
        new IndexColorModel(8, 2, levels, levels, levels));
DataBuffer buffer = new DataBufferByte(raw, raw.length);
SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width * 1, new int[]{0});
Raster raster = Raster.createRaster(sampleModel, buffer, null);
image.setData(raster);
ImageIO.write(image, "png", new File("test.png"));