1

So I just want to set a buffered image into a single background color is there a way to do this?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user7715
  • 97
  • 2
  • 9
  • 1
    *"is there a way to do this?"* Sure, but why would you want to? What feature does that supply to the app. that could not be done 3 better ways? – Andrew Thompson Jul 16 '12 at 23:40
  • Possible duplicate of [Set BufferedImage to be a color in Java](https://stackoverflow.com/questions/1440750/set-bufferedimage-to-be-a-color-in-java) – Suma Nov 17 '17 at 21:00

1 Answers1

7

Do you mean fill a BufferedImage with a background color? If so, here is an example on how to perform this:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestBufferedImage {

    private BufferedImage buffer;

    protected BufferedImage getBuffer() {
        if (buffer == null) {
            buffer = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = buffer.createGraphics();
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, buffer.getWidth(), buffer.getHeight());
            g.dispose();
        }
        return buffer;
    }

    protected void initUI() {
        final JFrame frame = new JFrame();
        frame.setTitle(TestBufferedImage.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel image = new JLabel(new ImageIcon(getBuffer()));
        frame.add(image);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestBufferedImage test = new TestBufferedImage();
                test.initUI();
            }
        });
    }

}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • 2
    +1, since there is lack of information from the part of the OP, as far as I understood it too, I guess this is what is expected and is the right answer :-) – nIcE cOw Jul 16 '12 at 16:16