Set BufferedImage to be a color in Java

前端 未结 5 976
既然无缘
既然无缘 2021-01-07 19:52

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 cr

5条回答
  •  长发绾君心
    2021-01-07 20:05

    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...

提交回复
热议问题