Search code examples
javaimagegraphics2d

Using Graphics2D to Manipulate an Image Multiple Times


I am trying to figure out how to take an image and use Graphics2D to manipulate it, all while being able to do multiple operations on the same image (so darkening it twice would make it darker than doing it once). Every single example I have found, is meant to manipulate an image once and display it. I need to be able to display the image multiple times. For example, let's say I have a menu with options 1, 2, 3, etc., and 1 darkens it, 2 lightens it and 3 displays the image.

How would I achieve this? I can get the image, darken it, rotate it and display it, but not with a menu or some other way of the user choosing when and what. If someone could link me to a webpage that does just that, or write a short (shorter is better), one class program to do what I described, I should be able to get going.

Basically, I need to be able to do something like this:

initialize image;
display(image);
lighten(image);

What I don't understand, is how I manipulate the image with the Graphics2D, and have it apply to my image.

This is what I have so far(mostly from here):

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class ShowImage extends JPanel {
Image img;

        public ShowImage() {
            super();
            img = Toolkit.getDefaultToolkit().getImage("image.png");
        }

        public void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.translate(170, 0);
            g2d.rotate(1);
            g2d.drawImage(img, 0, 0, this);
        }

        public static void main(String arg[]) {
            JFrame frame = new JFrame("Image Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(600, 400);

            ShowImage panel = new ShowImage();
            frame.setContentPane(panel);
            frame.setVisible(true);
    }
}

Currently, I am doing all the manipulation in paintComponent(), so it's not at all easy to manipulate. Is there a way to get the Graphics2D variable set up in the main, then get it into the paintComponent() somehow? I am completely lost as to how I would go about doing this.

I tried to post the links to all the webpages I viewed, but it won't let me post more than two links, because I am new.


Solution

  • If you need to manipulate an image in memory, create a BufferedImage and then call BufferedImage.createGraphics() to get access to a graphics object for drawing into the image's buffer.

    When you want to render that image onto a component in the UI, use the paintComponent() method of that component as you have done. Note that this involves two separate graphics objects, used for two different purposes.