简体   繁体   中英

How can I resize an image from a URL into a JPanel

try {
    addImage(bodyPanel1, "https://sneakernews.com/wp-content/uploads/2020/10/jordan-1-black-mocha-555088-105-2.jpg");
} catch (MalformedURLException e) {
    e.printStackTrace();
}


private void addImage(JPanel cp, String url) throws MalformedURLException{
    cp.add(new JLabel(new ImageIcon(new URL(url))));
}

So I am trying to insert the image using a URL and then have it resize to the size of the bodypanel but whenever i try to run it the image doesnt scale itself. I have the entire bodypanel in a grid layout (3 row, 2 columns) and want to add an image to fit the entire size of one of the grid boxes. image

Try this code I found ( Link to code | Link to the guy who originally found this code ):

ImageIcon imageIcon = new ImageIcon(new URL(url)); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);
cp.add(new JLabel(imageIcon));
    ImageIcon originalIcon = new ImageIcon("slovakia.png");
    JLabel originalLabel = new JLabel(originalIcon);

    int width = originalIcon.getIconWidth() / 2;
    int height = originalIcon.getIconHeight() / 2;

    Image scaled = scaleImage(originalIcon.getImage(), width, height);

    ImageIcon scaledIcon = new ImageIcon(scaled);

    JLabel newLabel = new JLabel(scaledIcon);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM