Search code examples
javaimageswingpaintcomponent

How to resize the image drawn on the Panel in JavaSwing?


I'm learning JavaSwing. I wanted to draw an Image on the frame, but I want the picture resolution drawn to be like 300*300. Here is my code for drawing an Image on the panel.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Picture 
{
    JFrame frame;
    public static void main(String[] args)
    {
        Picture poo = new Picture();
        poo.go();
    }
    private void go()
    {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.getContentPane().add(new ImageOne());
    }
    class ImageOne extends JPanel
    {
        public void paintComponent(Graphics g)
        {
            Image img = new ImageIcon("image.jpg").getImage();
            g.drawImage(img, 2, 2, this);
        }
    }
}

Can anyone tell me how to do this? I searched the net, but I could find explanations relating to BufferedImage, and I don't know how to use that.
Thanks in advance.


Solution

  • I believe you are looking for image.getScaledInstance(w,h, type). This scales the image to the given width (w) and height (h) to the type of scaling. The scaling type you would want to use is Image.SCALE_DEFAULT. Due to the way getScaledInstace works you have to create a new BufferedImage.

    So your code would look something like this

            BufferedImage img = null;
            try {
                img = ImageIO.read(new FileInputStream(new File("image.jpg")));
            } catch (Exception e) {}
    
            //Scale image to 300x300
            int width = 300;
            int height = 300;
            Image scaled = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
    
            //Create new buffered image
            BufferedImage tempBuff = new BufferedImage(width, height, img.getType());
    
             // Create Graphics object
            Graphics2D tempGraph = tempBuff.createGraphics();
            // Draw the resizedImg from 0,0 with no ImageObserver then dispose
            tempGraph.drawImage(scaled,0,0,null);
            tempGraph.dispose();
    
            g.drawImage((Image)tempBuff, 2, 2, this);