简体   繁体   中英

java drawImage turns complete black

I'm pasting plenty of face images (face_50xx.png) to the one big canvas (Faces.png) using drawImage(),

but every face turns into the whole black.

Here is my source code:

import java.io.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Color;


public class maa{

static BufferedImage in;
static BufferedImage out;

public static void main(String[] args) {
    String A = "face_";
    String B = "png";
    int j = 0;

    try{
        in = ImageIO.read(new File(A + 5001 + "." + B));
    }
    catch(java.io.IOException e){
    }




    out = new BufferedImage(1920, 14592, in.getType());


    for(int i = 1; i < 760; i++){
        String num;
        j = i + 5000;
        num = Integer.toString(j);
        try{
            in = ImageIO.read(new File("face_" + num + "." + "png"));
            Graphics g = in.getGraphics();
            g.drawImage(out, (i%10)*192, (i/10)*192, null);

        }
        catch(java.io.IOException e){
            continue;
        }
    }
    try{
        ImageIO.write(out,"png",new File("Faces." + B));
    }
    catch(java.io.IOException e){

    }
}


}

Please teach me what's the problem. Thanks.

  • You are doing absolutely nothing to the out image, and so when you write it to file, it will be blank.
  • You appear to be drawing on the wrong image. You want to get the Graphics object, g, from the out image, and draw the in images onto out.
  • You should never ignore exceptions as you are doing. At least print out a stack trace:

eg,

catch(IOException e) {
  e.printStackTrace();
}

The basic structure of your program should be:

create out image
get Out's Graphics object, g
for Loop through all of the `in` images
  Draw each in image onto out using out's Graphics context, g
end for loop
dispose of g
Write the out image to file

Edit: You state in comment,

Graphics g = in.getGraphics(); is a command that transporting the in image into g, isn't it?

No, you've got things backwards. Think of the Graphics object, g, as a pen that allows you to draw onto the image that you obtained it from. So a Graphics object, g, from an in image allows me to draw on the in image.

replace:

Graphics g = in.getGraphics();
            g.drawImage(out, (i%10)*192, (i/10)*192, null);

by: in.getGraphics().drawImage(out, (i%10)*192, (i/10)*192, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM