我下面的Java代码的目标是以400 X 400格式导出图像。现在,代码确实导出了图像。但是,它以原始大小导出图像。我不知道为什么它不能以所需的格式导出。没有错误。目标只是一些如何获得线
BufferedImage scaledButtonImage =新的BufferedImage(400,400,bimg.getType());
以它的方式工作。
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ren {
Frame f;
JLabel b2=new JLabel("");;
ren() throws IOException{
f=new JFrame();
b2.setIcon(new ImageIcon("/Users/johnzalubski/Desktop/dropIn/Complete-Audi-Buying-Guide-gear-patrol-lead-full.jpg"));
JButton b3 = new JButton("Exported");
File file = new File("aa.png");
f.add(b2,BorderLayout.CENTER);
f.add(b3,BorderLayout.SOUTH);
f.setSize(400,500);
f.setVisible(true);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Icon ico = b2.getIcon();
// Create a buffered image
BufferedImage bimg = new BufferedImage(ico.getIconWidth(), ico.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
// Create the graphics context
Graphics g = bimg.createGraphics();
// Now paint the icon
ico.paintIcon(null, g, 0, 0);
g.dispose();
BufferedImage scaledButtonImage =
new BufferedImage(400, 400, bimg.getType());
Graphics g1 = scaledButtonImage.createGraphics();
g1.drawImage(scaledButtonImage, 0, 0, 400, 400, null);
//
g1.dispose();
b2.setIcon(new ImageIcon(bimg));
try {
ImageIO.write(bimg, "png",file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
public static void main(String[] args) throws IOException {
new ren();
}
}
如果要在bimg
中创建scaledButtonImage
的缩放版本,则此行: