简体   繁体   中英

A simple way to setting a bufferedImage into a single colored pixel without placing a image into it?

所以我只想将缓冲的图像设置为单一背景色,有没有办法做到这一点?

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();
            }
        });
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM