skip to Main Content

I’ve been reading the API for Graphics2D and have seen examples of all the available composite modes (that are similar to photoshop blend modes) but I can’t see a way to draw a source image to a target buffered image In a colour that I have specified, for example my source image is a white opaque circle on a fully transparent background, how do I draw using this to a buffer so a coloured circle is drawn.

I would prefer not to construct an intermediate image for performance reasons, is this possible with the api?

EDIT: I have added an image that hopefully helps to show the operation I am trying to describe. This is a common way to draw sprites in open GL etc and I am just wondering how to use the Graphics2D API to do the same thing.

enter image description here

2

Answers


  1. Specify the location of your image in the imageName below.

    public class ColoredCircle extends JPanel {
    
       JFrame        frame     = new JFrame();
    
       BufferedImage buf;
       String        imageName = "F://ngc_1300_spiral.jpg";
    
       public static void main(String[] args) {
          new ColoredCircle().start();
       }
    
       int scale = 10;
    
       public void start() {
          try {
             buf = ImageIO.read(new File(imageName));
          }
          catch (IOException ioe) {
             ioe.printStackTrace();
          }
          setPreferredSize(
                new Dimension(buf.getWidth() / scale, buf.getHeight() / scale));
          frame.add(this);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          repaint();
       }
    
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g.create();
          g2d.drawImage(buf,
                0,
                0,
                buf.getWidth() / scale,
                buf.getHeight() / scale,
                null);
          g2d.dispose();
    
       }
    }
    
    Login or Signup to reply.
  2. Is is possible using the API but you have to write your own ImageProducer subclass similar to FilteredImageSource but with two input images instead of one. But because of that the end result will require more lines of code than a manual implementation and won’t be any more efficient. Alternatively you can use the existing FilteredImageSource and write an ImageFilter subclass that wraps the 2nd image and does the hard work.

    Poke me if you decide you want to go with any of these routes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search