我有一个尺寸为[10] [5]的2D数组,我试图将其转换为图像。这是我尝试过的代码,但它似乎并没有保存图像。我做错了什么?
public class GrayScale {
BufferedImage image;
int width;
int height;
public GrayScale() {
try {
int[][] yourmatrix = new int[][]{
{ 0, 1, 0, 0, 234, 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 45, 0, 0, 0, 0, 0, 231, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 89, 0, 0, 0, 1 }
};
width = yourmatrix.length;
height = yourmatrix[0].length;
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
int u = yourmatrix[i][j];
image.setRGB(j,i,u);
}
}
File ouptut = new File("C:\\Users\\Pratik\\Desktop\\UPWORK\\JAVA\\grayscale.jpg");
ImageIO.write(image, "jpg", ouptut);
} catch (Exception e) {}
}
static public void main(String args[]) throws Exception{
GrayScale obj = new GrayScale();
}
}
答案 0 :(得分:1)
初始化宽度和高度后,您必须初始化BufferedImage
:
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
图片类型可能会有所不同,但由于构造函数的名称为GrayScale
,我认为您需要TYPE_BYTE_GRAY
。
答案 1 :(得分:0)
工作示例:
public class GrayScale {
int width;
int height;
BufferedImage image;
GrayScale() {
try {
int[][] yourmatrix = new int[][]{
{ 0, 1, 0, 0, 234, 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 45, 0, 0, 0, 0, 0, 231, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 89, 0, 0, 0, 1 }
};
width = yourmatrix[0].length;
height = yourmatrix.length;
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
int u = yourmatrix[i][j];
image.setRGB(j,i,u);
}
}
File ouptut = new File("C:\\Others\\grayscale.jpg");
ImageIO.write(image, "jpg", ouptut);
}
catch (Exception e)
{
}
}
}
更正:
1.宽度和高度组件重新排列
2.在正确的地方定义的“图像”对象