My java code below's goal is to export a image in a 400 X 400 format. Right now the code does export a image. However it exports the image in its original size. I don't know why it does not export in its desired format. There are no errors present. The goal is just to some how get line
BufferedImage scaledButtonImage = new BufferedImage(400, 400, bimg.getType());
to work in its way.
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();
}
}
If you want to create a scaled version of
bimginscaledButtonImagethen this line:should be:
Currently your code is drawing
scaledButtonImageinto itself. Also, if you want to get a scaled copy ofbimgyou have to use the version ofdrawImagethat lets you specifiy the destination and source rectangles.Finally, you need to write out the
scaledButtonImage, notbimg. Change this lineto