任务是创建24位RGB ppm图像并将其存储在字节数组中。看起来很简单,我用jpg做到了,并且在第一次尝试中就正确了。 ppm虽然似乎没有复制到文件,但文件已创建但为空。我将其从FileOutputStream
更改为BufferedWriter
,但还是一无所有。
public class test
{
private static int width = 100;
private static int height = 100;
private static String matrix="";
public static void main (String[]args) {
matrix +="P6\t" + width + "\t" + height + "\t255\t";
for (int x=0; x<=height; x++) {
for ( int y=0; y<=width; y++) {
int R = (int) (Math.random()*256);//(Math.min(x,height-x)/ height * 2)*256;
int G = 0;
int B = 0;
int val = (int)(R<<16) | (G<<8) | B;
matrix += ""+val+"\t" ;
}
matrix +="\n";
}
try {
//FileOutputStream fos = new FileOutputStream("Imagee.jpg");
BufferedWriter fos = new BufferedWriter(new FileWriter("Imagee.jpg"));
for (int x=0; x<=height; x++) {
for ( int y=0; y<=width; y++) {
fos.write(Integer.toHexString(Byte.toUnsignedInt(matrix.getBytes()[y]))+"\t");
}fos.newLine();
}
fos.close();
if(fos==null){System.out.println("Image has not been created correctly");}
} catch(IOException error) {
System.out.println("\nError!");
error.getCause();
}
}
}
当我调试时,确实看到字符串中有值,我怀疑它们没有正确存储在文件中。任何帮助将不胜感激。