Scale an ImageTag(s): AWT
import java.awt.image.*; import java.awt.*; import java.net.*; public class app extends java.applet.Applet { Image source; Image resizedImage; public void init() { MediaTracker media = new MediaTracker(this); // java how-to image for example, can be JPG source = getImage(getDocumentBase(),"../images/jht.gif"); media.addImage(source,0); try { media.waitForID(0); // scale down, half the original size ImageFilter replicate = new ReplicateScaleFilter (source.getWidth(this)/2, source.getHeight(this)/2); ImageProducer prod = new FilteredImageSource(source.getSource(),replicate); resizedImage = createImage(prod); media.addImage(resizedImage,1); media.waitForID(1); } catch(InterruptedException e) {} } public void paint(Graphics g) { g.drawImage(source, 10,10,this); g.drawImage(resizedImage,10, 80,this); } }
Try it here.
Modern JDK has now a complete library devoted to graphic manipulation.
The following exampe takes a JPG file as input , rescale it to the passed parameters and writes the result in the specified output file.
import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; public class ScaleJPG { public static void scale(String src, int width, int height, String dest) throws IOException { BufferedImage bsrc = ImageIO.read(new File(src)); BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance((double)width/bsrc.getWidth(), (double)height/bsrc.getHeight()); g.drawRenderedImage(bsrc,at); ImageIO.write(bdest,"JPG",new File(dest)); } public static void main(String[] args) { if (args.length == 4) { try { ScaleJPG.scale (args[0],Integer.parseInt(args[1]), Integer.parseInt(args[2]), args[3]); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("\nUsage: java ScaleJPG src width height dest\n"); } } }
Example :
>java ScaleJPG javahowto.jpg 250 70 javahowto2.jpg
Ouput: