我正在加载一个 BufferedImage 并在其上绘制一个矩形。然后我想将结果保存为png
. 但图像不会使用ImageIO.write
. 我不认为我正在正确绘制图像。我当前的代码如下:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.io.*;
import java.sql.*;
import java.awt.Graphics2D;
public class goal extends Applet implements MouseListener, ActionListener {
Connection connection = null;
BufferedImage img = null;
Label ld;
URL url;
int x, y, w, h, entry, x2, y2, w2, h2;
double temp;
String id;
TextField percent;
Button enter;
Boolean save = false;
File outputfile = new File("C:/java temp/saved.png");
public void init() {
Graphics g = getGraphics();
addMouseListener(this);
this.setLayout(null);
x = 87;
y = 461;
w = 22;
h = 0;
percent = new TextField();
percent.setBounds(10, 10, 50, 30);
this.add(percent);
percent.setVisible(true);
percent.addActionListener(this);
enter = new Button("ENTER");
enter.setBounds(65, 10, 50, 30);
enter.addActionListener(this);
this.add(enter);
enter.setBackground(Color.blue);
enter.setVisible(true);
id = ("sales-goal.png");
try {
URL url = new URL(getCodeBase(), id);
img = ImageIO.read(url);
} catch (IOException e) {
}
}
public void paint(Graphics g) {
// Graphics2D g=img.createGraphics();
g.drawImage(img, 10, 10, this);
// g.drawImage(img,null,10,10);
Color myColor = Color.decode("#32004b");
g.setColor(myColor);
g.fillRect(x, y, w, h);
// g.fillRect(83,451,26,10);
if (entry >= 60) {
g.fillRect(x2, y2, w2, h2);
}
}
public void actionPerformed(ActionEvent e) {
Graphics g = getGraphics();
if (e.getSource() == percent) {
entry = Integer.parseInt(percent.getText());
if (entry < 101) {
y = 461;
temp = entry;
temp = temp * 2.65;
temp = Math.round(temp);
h = (int) temp;
y = y - h;
}
}
if (e.getSource() == enter) {
g.drawString(outputfile + "", 10, 10);
save = true;
try {
ImageIO.write(img, "png", outputfile);
} catch (IOException i) {
}
}
repaint();
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
{
}
}