Originariamente inviato da Patrick Jane
Secondo te cosa può causare questa sorta di scambio di colori?
Guarda, così su due piedi non ti so dire, anche perché dovrei vedere bene tutto quello che hai scritto in modo completo (non frammentato come hai postato finora).
Io ho fatto una mia prova:
codice:
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
PPMImage ppmImg = new PPMImage(200, 200);
for (int x = 0; x < 200; x++) {
ppmImg.setPixel(x, 0, 255, 0, 0);
ppmImg.setPixel(x, 10, 0, 255, 0);
ppmImg.setPixel(x, 20, 0, 0, 255);
}
ppmImg.write(new File("test.ppm"));
} catch (Exception e) {
System.err.println(e);
}
}
}
class PPMImage {
private byte[] data;
private int width;
private int height;
public PPMImage(int width, int height) {
data = new byte[width * height * 3];
this.width = width;
this.height = height;
}
public void setPixel(int x, int y, int red, int green, int blue) {
if (x < 0 || x >= width) {
throw new IllegalArgumentException("x out of range");
}
if (y < 0 || y >= height) {
throw new IllegalArgumentException("y out of range");
}
int i = (y * width + x) * 3;
data[i] = (byte) red;
data[i+1] = (byte) green;
data[i+2] = (byte) blue;
}
public void write(File f) throws IOException {
FileOutputStream fos = new FileOutputStream(f);
String header = "P6\n" +
"#Image by PPMImage java class\n" +
width + " " + height + "\n" +
"255\n";
try {
fos.write(header.getBytes("US-ASCII"));
fos.write(data);
} finally {
fos.close();
}
}
}
La immagine la scrive correttamente e la "vedo" perfettamente sia con GIMP che con IrfanView: tutta nera con una riga rossa, poi una verde, poi una blu.
Nota comunque come ho lanciato una eccezione in setPixel e come ho fatto la scrittura usando solo FileOutputStream e gestendo anche correttamente la chiusura dello stream.