In the following code, I'm trying to combine some 1024*1024 png into several larger pngs. The code fails with this exception:
Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to [I
at sun.awt.image.IntegerInterleavedRaster.setDataElements(Unknown Source)
at java.awt.image.BufferedImage.copyData(Unknown Source)
at mloc.bs12.mapimagemerger.Merger.main(Merger.java:27)
It's probably something small and silly which I overlooked, but I can't find anything wrong with the code. Code:
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class Merger {
public static void main(String[] args) {
String toX, toY, toZ;
try {
toX = args[0];
toY = args[1];
toZ = args[2];
} catch(ArrayIndexOutOfBoundsException E) {
//E.printStackTrace();
toX = "3";
toY = "5";
toZ = "4";
}
int yproper = 1;
for(int z = 1; z <= Integer.parseInt(toZ); z++) {
BufferedImage img = new BufferedImage(Integer.parseInt(toX) * 1024, Integer.parseInt(toY) * 1024, BufferedImage.TYPE_INT_RGB);
for(int x = 1; x <= Integer.parseInt(toX); x++) {
for(int y = 1; y <= Integer.parseInt(toY); y++) {
BufferedImage simg = img.getSubimage(x*1024, y*1024, 1024, 1024);
BufferedImage tempimg = loadImage(x + "-" + y + "-" + z + ".png");
WritableRaster rsimg = simg.getRaster();
开发者_如何转开发 rsimg = tempimg.copyData(rsimg); <-- Error!
yproper++;
}
}
saveImage(img, z + ".png");
}
}
public static BufferedImage loadImage(String path) {
BufferedImage bimg = null;
try {
bimg = ImageIO.read(new File(path));
} catch (Exception e) {
e.printStackTrace();
}
return bimg;
}
public static void saveImage(BufferedImage img, String path) {
try {
ImageIO.write(img, "png", new File(path));
} catch (Exception e) {
e.printStackTrace();
}
return;
}
}
I think I have this figured out by now. The images I was loading were not the same type as the image I created. (I'm still not sure what type they are, what is the 13 type?) I have some more problems, but this error is fixed. (More problems, as in this.)
The library casts a byte array to an int array, which you cannot do.
I am unfamiliar with BufferedImage but a qualified guess would be that the PNG file you read in, is treated as byte values instead of integer values.
精彩评论