I am trying to take severial jpg images with the same dimensions(30*30) and create a single image. Like this:
Image i = new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) i.getGraphics();
if (this instanceof Node) {
Image img;
img = getImageFromFile(Node.icon);
g2.drawImage(img, 0, 0, null);
}
if(this instanceof ForceNode){
Image img;
img = getImageFromFile(ForceNode.forceicon);
g2.drawImage(img, 0, 0, null);
}
if(this instanceof TunnelNode){
Image img;
img = getImageFromFile(TunnelNode.tunnelicon);
g2.drawImage(img, 0, 0, null);
}
....
public Image getImageFromFile(File file) {
Image image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
Logger.getLogger(HackerGame.class.getName()).log(Level.SEVERE, null, e);
return null;
}
return image;
}
I realize there are some issues with G2D not being strictly necessary, but my issue is this: These images needs to be put on top of each other to create a whole image. Eash of the images are small areas of the whole picture, that needs to be put on top of(Not next to) each other to create the actual image. The problem right now however is that the last drawImage method overwrites the entire image, so i am left with the last "bit of image" instead of my compiled image.
I suspect this is because the white areas of my pictures are not being treated as transparent, but how do i get around this. I have next to no experience with image encoding so i am sort of going by trial and error:) Anyway开发者_如何转开发 HELP!
Solution:
public void generateIcon() {
BufferedImage i = new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB);
if (this instanceof Node) {
i = compileImages(i, Node.icon);
}
if(this instanceof ForceNode){
i = compileImages(i, ForceNode.forceicon);
}
if(this instanceof TunnelNode){
i = compileImages(i, TunnelNode.tunnelicon);
}
if (this instanceof EntranceNode) {
i = compileImages(i, EntranceNode.entranceicon);
}
if (this instanceof NetworkNode) {
i = compileImages(i, NetworkNode.networkicon);
}
if(this instanceof DataNode){
i = compileImages(i, DataNode.dataicon);
}
//if(this instanceof )
nodeicon = i;
}
public BufferedImage compileImages(BufferedImage image, File f) {
BufferedImage im = null;
try {
im = ImageIO.read(f);
for(int i = 0 ; i<image.getWidth();i++){
for(int j = 0 ; j<image.getHeight();j++){
int rgb = im.getRGB(i, j);
//System.out.println(i + " " + j + " " + rgb);
if(!(rgb < 1 && rgb > -2)){
image.setRGB(i, j, rgb);
//System.out.println("Printing " + i + " " + j + " " + rgb);
}
}
}
} catch (IOException e) {
Logger.getLogger(HackerGame.class.getName()).log(Level.SEVERE, null, e);
return null;
}
return image;
}
Iterate the pixels of the source images. If they are not white (use getRGB(x,y)
to compare them), write them to the destination image.
精彩评论