如何在Java中创建图像 [英] How to create image in Java

查看:43
本文介绍了如何在Java中创建图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中说,我有这个paint()方法.我的愿望是创建所绘制矩形的图像(使用 for 循环).我尝试了下面的方法,它确实给了我那些矩形(蓝色),但背景全是黑色.当我在不创建图像的情况下运行程序时,只需在 JFrame 上绘制矩形,背景为白色.我怎样才能解决这个问题.?

say in my program, i have this paint() method. my wish is to create an image of the rectangles that are drawn (with the for loop). I tried the method below and it did give me those rectangles (blue color), but the background is all black. When I run program without creating image, just drawing the rect on a JFrame, the background is white. How can i fix this. ?

public void paint(Graphics g) {     
    super.paint(g);
    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    g = Image.getGraphics();  <<<----- is this correct?
    g.setColor(Color.blue);
    for ( ..... ) {
        g.fillRect(X , Y,  width , height);
            ....        
    }
    try {
    ImageIO.write(image, "jpg", new File("CustomImage.jpg"));
    }catch (IOException e) { 
       e.printStackTrace();
    }
}

推荐答案

图像中的背景是黑色的,因为除了矩形中的像素之外,您没有为任何像素指定值.BufferedImage 开始时每个像素的 RGB 为 (0, 0, 0),即黑色.要为整个图像提供白色背景,只需用白色填充图像的整个矩形即可.

The background is black in your image because you are not giving any pixels a value except those in the rectangles. The BufferedImage is starting out with every pixel having RGB of (0, 0, 0), which is black. To give the entire image a white background, simply fill the entire rectangle that is the image with white.

BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
g = image.createGraphics();  // not sure on this line, but this seems more right
g.setColor(Color.white);
g.fillRect(0, 0, 100, 100); // give the whole image a white background
g.setColor(Color.blue);
for( ..... ){
    g.fillRect(X , Y,  width , height );
        ....        
}

请注意,我的回答是将图像写入白色背景的文件,而不是绘制到黑色背景的 JFrame.我不完全确定你想要哪一个.

Note that my answer is about writing the image to a file with a white background, not about drawing to the JFrame with a black background. I'm not entirely sure which one you wanted.

这篇关于如何在Java中创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆