将 BufferedImage 设置为 Java 中的一种颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1440750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set BufferedImage to be a color in Java
提问by Lily
I need to create a rectangular BufferedImage
with a specified background color, draw some pattern on the background and save it to file. I don't know how to create the background.
我需要创建一个BufferedImage
具有指定背景颜色的矩形,在背景上绘制一些图案并将其保存到文件中。我不知道如何创建背景。
I am using a nested loop:
我正在使用嵌套循环:
BufferedImage b_img = ...
for every row
for every column
setRGB(r,g,b);
But it's very slow when the image is large.
但是当图像很大时它很慢。
How to set the color in a more efficient way?
如何以更有效的方式设置颜色?
采纳答案by Pete Kirkham
Get the graphics object for the image, set the current paint to the desired colour, then call fillRect(0,0,width,height)
.
获取图像的图形对象,将当前绘制设置为所需的颜色,然后调用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() );
回答by camickr
Probably something like:
大概是这样的:
BufferedImage image = new BufferedImage(...);
Graphics2D g2d = image.createGraphics();
g2d.setColor(...);
g2d.fillRect(...);
回答by Aaaaaaaa
Use this:
用这个:
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
ig2.setBackground(Color.WHITE);
ig2.clearRect(0, 0, width, height);
回答by hoford
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
int[]data=((DataBufferInt) image.getRaster().getDataBuffer()).getData();
Arrays.fill(data,color.getRGB());
回答by Juan Franco
For who want also to save the created image to a file, I have used previous answers and added the file saving part:
对于谁还想将创建的图像保存到文件中,我使用了以前的答案并添加了文件保存部分:
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);
You can also save the image in other formats like bmp, jpg, etc...
您还可以将图像保存为其他格式,如 bmp、jpg 等...