Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resizing image java getScaledInstance

Tags:

java

image

here is my code"

ImageIcon ii=new ImageIcon("/Users/tushar_chutani/Desktop/apple.jpg");  

Image image= ii.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);

the image is not being scaled what is wrong with the code?

like image 550
Tushar Chutani Avatar asked Aug 31 '11 05:08

Tushar Chutani


People also ask

Can you resize an image in Java?

You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We'll use the BufferedImage class that extends the basic Image class. It stores images as an array of pixels.

How do I make an image smaller in Java Swing?

Just do: Image newImage = yourImage. getScaledInstance(newWidth, newHeight, Image. SCALE_DEFAULT);

How do I resize an image in an applet?

* To resize an applet window use, * void resize(int x, int y) method of an applet class.


1 Answers

The problem is that Image.getScaledInstance() does not return a finished, scaled image. It leaves much of the scaling work for a later time when the image pixels are used.

For example, if you use the scaled image in a Graphics2D.drawImage() call then the method will return false and continue drawing asynchronously. You then have to use the ImageObserver parameter in the Graphics2D.drawImage() call to wait for completion of the scaling and drawing.

The following example shows how to scale images more simply without an ImageObserver. The scaling is done by drawing the icon into a BufferedImage instead.

import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.Color;
import java.awt.Graphics2D;
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.RenderingHints;

public class Tushar2
{
        public void scaleImage()
        {
                try
                {
                        ImageIcon ii = new ImageIcon("/tmp/apple.jpg");
                        BufferedImage bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = (Graphics2D)bi.createGraphics();
                        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,
                                RenderingHints.VALUE_RENDER_QUALITY));
                        boolean b = g2d.drawImage(ii.getImage(), 0, 0, 50, 50, null);
                        System.out.println(b);
                        ImageIO.write(bi, "jpg", new File("/tmp/apple50.jpg"));
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                }
        }

        public static void main(String []args)
        {
                new Tushar2().scaleImage();
        }
}
like image 67
Simon C Avatar answered Sep 22 '22 15:09

Simon C