5

I have some .jpg's that I'm displaying in a panel. Unfortunately they're all about 1500x1125 pixels, which is way too big for what I'm going for. Is there a programmatic way to change the resolution of these .jpg's?

Matt Razza
  • 3,524
  • 2
  • 25
  • 29
Quintis555
  • 659
  • 3
  • 11
  • 16

3 Answers3

5

You can scale an image using Graphics2D methods (from java.awt). This tutorial at mkyong.com explains it in depth.

toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
3

Load it as an ImageIcon and this'll do the trick:

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;

public static ImageIcon resizeImageIcon( ImageIcon imageIcon , Integer width , Integer height )
{
    BufferedImage bufferedImage = new BufferedImage( width , height , BufferedImage.TRANSLUCENT );

    Graphics2D graphics2D = bufferedImage.createGraphics();
    graphics2D.drawImage( imageIcon.getImage() , 0 , 0 , width , height , null );
    graphics2D.dispose();

    return new ImageIcon( bufferedImage , imageIcon.getDescription() );
}
Jonathan Payne
  • 2,223
  • 13
  • 11
  • Oh man, I WAS going to check tom off as an answer, but I AM already using ImageIcon, so this might be more what I need. STAND BY FOR FUTURE EXCITING UPDATES! – Quintis555 Jul 19 '12 at 15:08
  • I'm getting an "error: cannot find symbol" on this line BufferedImage bufferedImage = new BufferedImage( width , height , BufferedImage.TRANSLUCENT); It points to the BufferedImage part in the build output window. – Quintis555 Jul 19 '12 at 15:15
  • I'm not sure, it compiles fine on mine. What IDE are you using? – Jonathan Payne Jul 19 '12 at 15:21
  • JCreator LE. Is there some import I'm missing? – Quintis555 Jul 19 '12 at 15:23
  • I added the imports to the answer. – Jonathan Payne Jul 19 '12 at 15:25
  • Great. Not getting build errors anymore! But... it's not doing anything. I need to make sure I'm doing this right... I set the ImageIcon line: 'ImageIcon icon = new ImageIcon("...\\J02406-TOP.jpg");' Then call resizeImageIcon? 'resizeImageIcon(icon, 500, 400);' – Quintis555 Jul 19 '12 at 15:32
1

you can try:

private BufferedImage getScaledImage(Image srcImg, int w, int h) {
    BufferedImage resizedImg = new BufferedImage(w, h, Transparency.TRANSLUCENT);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}                         
UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
ewok
  • 20,148
  • 51
  • 149
  • 254