我正在尝试自动将Java小程序的图形内容保存到图像文件中,但我遇到了一个问题,即该文件没有正确保存。我完整的Java代码是:
package nl.mark.SierpinskiCarpet;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SierpinskiCarpet extends Applet {
private Graphics g = null;
private int d0 = 729; // 3^6
private BufferedImage bufferedImage;
private final GraphicsConfiguration gConfig = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
public void init() {
g = getGraphics();
resize(d0, d0);
}
public void paint(Graphics g) {
drawSierpinskiCarpet(0, 0, getWidth(), getHeight());
storeImage();
}
public void storeImage() {
BufferedImage image = create(d0, d0, true);
Graphics2D g = image.createGraphics();
// you can disable this if you don't want smooth graphics
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawSierpinskiCarpet(0, 0, getWidth(), getHeight());
g.dispose();
try {
ImageIO.write(image, "png", new File(
"N:\\Tapijt van Sierpiński\\image.png"));
} catch (IOException e) {
}
}
private void drawSierpinskiCarpet(int xOL, int yOL, int breedte, int hoogte) {
if (breedte > 2 && hoogte > 2) {
int b = breedte / 3;
int h = hoogte / 3;
g.fillRect(xOL + b, yOL + h, b, h);
for (int k = 0; k < 9; k++)
if (k != 4) {
int i = k / 3;
int j = k % 3;
drawSierpinskiCarpet(xOL + i * b, yOL + j * h, b, h);
}
}
}
private BufferedImage create(final int width, final int height,
final boolean alpha) {
BufferedImage buffer = gConfig.createCompatibleImage(width, height,
alpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
return buffer;
}
}
小程序中显示的图像(Sierpinski Carpet)是正确的,但创建的文件只是空白图像。要绘制模式,调用drawSierpinskiCarpet()方法,在执行该函数后,调用函数storeImage()来保存图像,但会在输出目录中生成空白图像文件。保存图像时出了什么问题?
答案 0 :(得分:1)
您应该从不在组件上调用getGraphics
(并且从不存储作为参数提供的Graphics
对象{{1 }}左右)。
(你永远不应该默默地吞下一个paint
。至少添加一些IOException
来了解什么时候出错了。
此处的问题是您从图片中获取了e.printStackTrace()
对象,但对Graphics
的调用仍然使用了作为该类字段存储的drawSierpinskiCarpet
。
在这种情况下,一个简单的解决方案是通过递归调用将Graphics g
对象作为参数传递:
Graphics