Java: Load image from file, edit and add to JPanel

前端 未结 3 1574
陌清茗
陌清茗 2021-01-28 05:40

I want to load an image from my computer into 2D Graphics so that I can edit it afterwards and then I want to add it to JPanel. If you need to see my project I can

3条回答
  •  伪装坚强ぢ
    2021-01-28 05:41

    To load your image into the memory, you can use ImageIO.read(File). To edit it afterwards, obtain a Graphics2D instance from it by calling createGraphics():

    BufferedImage img = ImageIO.read(yourFile);
    Graphics2D g = img.createGraphics();
    // Draw here on the graphics
    g.dispose();
    

    You can even turn on anti-alias by setting a RenderingHint before drawing:

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                       RenderingHints.VALUE_ANTIALIASING_ON);
    

    Then, to add it to a JPanel, create your custom JComponent and add an instance of that component to your JPanel:

    public class JImageComponent extends JComponent
    {
        private BufferedImage img;
    
        public JImageComponent(BufferedImage bi)
        {
            img = bi;
        }
    
        @Override
        public void paintComponent(Graphics g)
        {
            g.drawImg(img, 0, 0, this);
        }
    
    }
    

提交回复
热议问题