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?
解决方案
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();
}
}