0

I'm Java beginner trying to load a .PNG 8356 x 5092 pixels into a JFrame 720 x 600.

I can load the image but it is zoomed to the top left, wanting to make the .PNG fit into the JFrame and then be able to span with the mouse click and zoom with mouse scroll.

I have been looking for answers for about 2 weeks now but no avail. Just wanting a good shove into the right direction...

Cheers

EDIT

Ok I got the Image to load and scale to size by doing:

public Image ScaledImage(Image img, int w, int h) {
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;

}

and passing it over to the JLabel like:

BufferedImage Map = ImageIO.read(new File(.PNG-LOCATION));
     ImageIcon icon = new ImageIcon(ScaledImage(Map, 720, 600));
            JLabel Label = new JLabel();
            Label.setIcon(icon);

Now just need help or guidance in zooming, click to drag

Thanks for the help

1 Answers1

0

Here is an example for resizing:

static BufferedImage createResizedCopy(Image originalImage, 
            int scaledWidth, int scaledHeight, 
            boolean preserveAlpha)
    {
        System.out.println("resizing...");
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha) {
            g.setComposite(AlphaComposite.Src);
        }
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
        g.dispose();
        return scaledBI;
    }

Use code above as: img2 = createResizedCopy(img, 720 , 600, true); Where img is your original image and img2 is the resized one.

To load img use: img = ImageIO.read(new File("yourImagepath"));

To show it in frame:

img2 = createResizedCopy(img, 720 , 600, true);
ImageIcon icon=new ImageIcon(img2);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(720,600);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

More details can be found here: resizing image in java

Community
  • 1
  • 1
betontalpfa
  • 3,454
  • 1
  • 33
  • 65