1

I do not know why this method does not work to resize an image. No errors occur (I have an exception if so):

   private static void resizeImage(int width, int height) {
        try {
            BufferedImage rawImg = ImageIO.read(new File("%imgg%.png"));
            int gamlaWidth = rawImg.getWidth();
            int gamlaHeight = rawImg.getHeight();
            BufferedImage dimg = new BufferedImage(width, height, rawImg.getType());
            Graphics2D g = rawImg.createGraphics();
            g.drawImage(rawImg, 0, 0, 114, 114, null);
            g.dispose();  
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Ett fel uppstod:\n" + e, "Felmeddelande", 0);
        }
    }  

Why doesn't this code change anything? I want the size to be 114x114.

1 Answers1

1

You could always use this code to resize an image.

Image smallerImage = null;
ImageIcon smallerImageIcon = null;
public void resizeImage(int width, int height, String image)

{
    ImageIcon originalImage = new ImageIcon(image);
    smallerImage = originalImage.getImage().getScaledInstance(width,height,0);
    smallerImageIcon = new ImageIcon(smallerImage);
}

Using this method if you wanted an image %imgg%.png to be 114 by 114 you would call the method like so

resizeImage(114, 114, "%imgg%.png");

With your code I believe the problem might be where you set it to 114 by 114 since that size is different to the scaled size.

Try

BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha)
{
    System.out.println("resizing...");
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
    g.dispose();
    return scaledBI;
}

Use

ImageIcon originalImage = new ImageIcon("%imgg%.png");
Image resizedImage = createResizedCopy(originalImage.getImage(),114,114,true);

See here

Community
  • 1
  • 1
Dan
  • 7,286
  • 6
  • 49
  • 114
  • But how do I replace the old image with the new, resized image? –  Dec 19 '15 at 11:46
  • @Stardox edited it so you declare the image before the method then run the method and after just call the correct variable – Dan Dec 19 '15 at 11:50
  • @Stardox I also added how to use the second method – Dan Dec 19 '15 at 11:53