【问题标题】:Set BufferedImage to be a color in Java将 BufferedImage 设置为 Java 中的颜色
【发布时间】:2010-11-29 06:30:33
【问题描述】:

我需要创建一个具有指定背景颜色的矩形BufferedImage,在背景上绘制一些图案并将其保存到文件中。我不知道如何创建背景。

我正在使用嵌套循环:

BufferedImage b_img = ...
for every row
for every column
setRGB(r,g,b);

但是图片很大的时候很慢。

如何更有效地设置颜色?

【问题讨论】:

    标签: java image graphics bufferedimage graphics2d


    【解决方案1】:

    获取图像的图形对象,将当前绘制设置为所需颜色,然后调用fillRect(0,0,width,height)

    BufferedImage b_img = ...
    Graphics2D    graphics = b_img.createGraphics();
    
    graphics.setPaint ( new Color ( r, g, b ) );
    graphics.fillRect ( 0, 0, b_img.getWidth(), b_img.getHeight() );
    

    【讨论】:

    • 不是setPaint,而是setColor
    • @Xdg docs.oracle.com/javase/7/docs/api/java/awt/… 颜色是一种颜料;但 setColor 也可以像其他答案一样工作
    • 你是对的,对不起。我使用的是 Graphics 而不是 Graphics2D。
    • 别忘了处理你的图形对象
    【解决方案2】:

    大概是这样的:

    BufferedImage image = new BufferedImage(...);
    Graphics2D g2d = image.createGraphics();
    g2d.setColor(...);
    g2d.fillRect(...);
    

    【讨论】:

      【解决方案3】:

      使用这个:

      BufferedImage bi = new BufferedImage(width, height,
                      BufferedImage.TYPE_INT_ARGB);
      Graphics2D ig2 = bi.createGraphics();
      
      ig2.setBackground(Color.WHITE);
      ig2.clearRect(0, 0, width, height);
      

      【讨论】:

        【解决方案4】:
        BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
        int[]data=((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        Arrays.fill(data,color.getRGB());
        

        【讨论】:

        • 更好地解释答案的更多细节
        • 当我在 Java 8 中尝试此操作时,我得到 java.lang.ClassCastException: java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
        • 该方法取决于您使用的实际图像的内部结构。 BufferedImage 可以有多种类型,具体取决于图像的来源。 DataBufferInt 顾名思义,它由一个 int 数组支持。对应类型BufferedImage.TYPE_INT_ARGB
        【解决方案5】:

        对于还想将创建的图像保存到文件的人,我使用了以前的答案并添加了文件保存部分:

        import java.awt.Color;
        import java.awt.Graphics2D;
        import java.awt.color.ColorSpace;
        import java.awt.image.BufferedImage;
        import javax.imageio.ImageIO;
        
        // Create the image
        BufferedImage bi = new BufferedImage(80, 40, ColorSpace.TYPE_RGB);
        Graphics2D graphics = bi.createGraphics();
        
        // Fill the background with gray color
        Color rgb = new Color(50, 50, 50);
        graphics.setColor (rgb);
        graphics.fillRect ( 0, 0, bi.getWidth(), bi.getHeight());
        
        // Save the file in PNG format
        File outFile = new File("output.png");
        ImageIO.write(bi, "png", outFile);
        

        您还可以将图像保存为其他格式,例如 bmp、jpg 等...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-06
          • 1970-01-01
          • 2012-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多