我在将图像加载到程序中时出现问题。我尽可能多地研究和解决问题,但我已经走到了尽头。我知道我加载图像的代码很接近但是加载文件时会出现一些奇怪的arrayoutofboundsexception。唯一的方法是从ppm文本文件中获取每个像素并逐个像素地绘制。我有下面的装载课程。文件类型必须保持不变,因为我必须通过单击按钮来读取它并更改像素,但我需要弄清楚这个原因以及它是否会妨碍保存图像的能力。
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileClass {
public int width;
public int height;
public int[] loadData(String filename) throws FileNotFoundException {
File foo = new File(filename);
Scanner scan = new Scanner(foo);
scan.nextLine();
scan.nextLine();
width = scan.nextInt();
height = scan.nextInt();
System.out.print(height);
scan.nextLine();
int[] array = new int [width * height];
int i = 0;
while (scan.hasNextInt()) {
array[i] = scan.nextInt();
i++;
System.out.print("yes");
}
scan.close();
return array;
}
public BufferedImage makeImage(int[] array){
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
int z = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int pixelColor = new Color(array[z], array[z+1], array[z+2]).getRGB();
image.setRGB(y, x, pixelColor);
z+=3;
}
}
return image;
}
}