I'm trying to make an image of a cake pop up on a button when you click a different button.
The part of the code I'm working on. I just want to resize the button.
if (e.getSource() == cake) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("cake.jpg"));
myPicture.getScaledInstance(800, 500, Image.SCALE_DEFAULT);
} catch (IOException e1) {
e1.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
cake.add(picLabel, BorderLayout.CENTER);
}
I tried scaling the image as shown and done other stuff from looking at other stack overflow and other websites but non of them have worked.
Like @g00se mentioned:
Creates a scaled version of this image. A new Image object is returned ...
So you need to assign its value back to myPicture
variable like this:
myPicture = myPicture.getScaledInstance(800, 500, Image.SCALE_DEFAULT);
By the way, this is a nice way to scale a picture but using AffineTransform
is much faster if you prefer. Here is the method I use for scaling images:
/**
* Scales the given image by the specified ratio
* using the AffineTransform method.
*
* @param source the original BufferedImage to be scaled.
* @param ratio the scaling ratio. A ratio greater than 1
* enlarges the image, less than 1 shrinks the image.
* @return a new BufferedImage that is a scaled version of
* the original image.
*/
private BufferedImage scaleImageFast(BufferedImage source, double ratio) {
BufferedImage bi = new BufferedImage(
(int) (source.getWidth() * ratio),
(int) (source.getHeight() * ratio),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(ratio, ratio);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
Also if the image is located on your res
folder you should use getResourcesAsStream()
method like this:
ImageIO.read(MyClass.class.getResourceAsStream("cake.jpg"));