How can I edit a jpg image through Java?

后端 未结 5 1427
名媛妹妹
名媛妹妹 2021-02-07 10:52

I have loaded a jpg image in which I want to draw letters and circles, given a x,y coordinate.

I have been trying to figure out the paintIcon of the ImageIcon class

<
5条回答
  •  执念已碎
    2021-02-07 11:33

    Manipulating images in Java can be achieved by using the Graphics or Graphics2D contexts.

    Loading images such as JPEG and PNG can be performed by using the ImageIO class. The ImageIO.read method takes in a File to read in and returns a BufferedImage, which can be used to manipulate the image via its Graphics2D (or the Graphics, its superclass) context.

    The Graphics2D context can be used to perform many image drawing and manipulation tasks. For information and examples, the Trail: 2D Graphics of The Java Tutorials would be a very good start.

    Following is a simplified example (untested) which will open a JPEG file, and draw some circles and lines (exceptions are ignored):

    // Open a JPEG file, load into a BufferedImage.
    BufferedImage img = ImageIO.read(new File("image.jpg"));
    
    // Obtain the Graphics2D context associated with the BufferedImage.
    Graphics2D g = img.createGraphics();
    
    // Draw on the BufferedImage via the graphics context.
    int x = 10;
    int y = 10;
    int width = 10;
    int height = 10;
    g.drawOval(x, y, width, height);
    
    g.drawLine(0, 0, 50, 50);
    
    // Clean up -- dispose the graphics context that was created.
    g.dispose();
    

    The above code will open an JPEG image, and draw an oval and a line. Once these operations are performed to manipulate the image, the BufferedImage can be handled like any other Image, as it is a subclass of Image.

    For example, by creating an ImageIcon using the BufferedImage, one can embed the image into a JButton or JLabel:

    JLabel l = new JLabel("Label with image", new ImageIcon(img));
    JButton b = new JButton("Button with image", new ImageIcon(img));
    

    The JLabel and JButton both have constructors which take in an ImageIcon, so that can be an easy way to add an image to a Swing component.

提交回复
热议问题