将bufferedImage设置为单个彩色像素而不将图像放入其中的简单方法?

时间:2012-07-16 09:41:49

标签: java swing jpanel jlabel bufferedimage

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

1 个答案:

答案 0 :(得分:6)

你的意思是用背景颜色填充BufferedImage吗?如果是这样,这里有一个如何执行此操作的示例:

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

}