【问题标题】:BufferedImage draw white when I say red当我说红色时,BufferedImage 绘制白色
【发布时间】:2011-08-16 03:38:00
【问题描述】:

这一定是一个非常愚蠢的解决方案,但我是盲人。

我有这个代码:

BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
bi.getGraphics().setColor(Color.red);
bi.getGraphics().fillRect(300, 350, 100, 50);
ImageIO.write(bi, "jpeg", new File("image.jpg"));

我得到了这个黑色的 800x600 矩形和一个白色矩形。这是为什么呢?

谢谢:)

【问题讨论】:

  • 为了详细说明 MBFG 的帖子,您将在每次调用 getGraphics 时创建一个新的 Graphics 对象,这两个对象彼此无关。而是按照他的建议创建一个 Graphics 对象。另外,完成后不要忘记将其丢弃。

标签: java image


【解决方案1】:

每次对 BufferedImage 调用 getGraphics() 时,都会得到一个新的 Graphics 对象,因此在一个对象上设置颜色,而不是在下一个对象上设置颜色。所以缓存图形对象。

BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.red);
g.fillRect(300, 350, 100, 50);
ImageIO.write(bi, "jpeg", new File("/home/dave/image.jpg"));

【讨论】:

  • 同意 1+。完成后在 Graphics 对象上添加调用 dispose 也是一个好习惯。
  • 谢谢!我假设它只是返回 Image 图形对象
  • +1 你打败了我,证明你更敏捷,是更大的胖子! :-)
  • @trashgod:我想你只 dispose() 你创建的 Graphics 对象?例如,从paintComponents 传递给您的图形对象不应该被释放,对吧?
  • @MBFG:是的,这是我的理解;我将发布示例以供参考。这是此类方法的list
【解决方案2】:

作为参考,这里有一个示例,可能有助于修改图形上下文。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @http://stackoverflow.com/questions/5843426 */
public class RedOrWhite extends JPanel {

    private static final int W = 800;
    private static final int H = 600;

    public RedOrWhite() {
        this.setLayout(new GridLayout());
        this.setPreferredSize(new Dimension(W, H));
        int w = W / 2;
        int h = H / 2;
        int r = w / 5;
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setColor(Color.gray);
        g.fillRect(0, 0, w, h);
        g.setColor(Color.blue);
        g.fillRect(w / 2 - r, h / 2 - r / 2, 2 * r, r);
        g.dispose();
        this.add(new JLabel(new ImageIcon(bi), JLabel.CENTER));
    }

    private void display() {
        JFrame f = new JFrame("RedOrWhite");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new RedOrWhite().display();
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 2014-12-21
    • 2018-03-31
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多