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

孤人 提交于 2020-01-05 04:43:24

问题


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


回答1:


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

}


来源:https://stackoverflow.com/questions/11501761/a-simple-way-to-setting-a-bufferedimage-into-a-single-colored-pixel-without-plac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!