简体   繁体   中英

Graphics.drawImage() not drawing image

    Image img = null;
    try {
        img = ImageIO.read(new File("pig.png"));
    } catch (IOException e){

    }
    Graphics g = img.getGraphics();
    g.drawImage(img, 0, 0, null);

I'm using this tutorial: https://docs.oracle.com/javase/tutorial/2d/images/

The program runs, but the image doesn't show up.

You have to use GUI component

You can simply use Swing,

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JComponent;
import javax.swing.JFrame;

class DemoPaint extends JComponent {

  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    Image picture = Toolkit.getDefaultToolkit().getImage("yourFile.gif");
    g2.drawImage(picture, 10, 10, this);
    g2.finalize();
  }
}

public class DrawImageGraphics {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new DemoPaint());
    window.setVisible(true);
  }
}

I hope this will help.

Once you loaded picture into Image object, create a buffered image with transparency

BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

Draw the image on to the buffered image

Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();

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