简体   繁体   中英

How to convert ImageIcon to Image?

I have grabbed the imageicon from my project src files like this:

 icon = new ImageIcon(ViewDetailsV.class.getResource("/brandnew/images/male_avatar.jpg"));

Then I want to put into this line so as to resize to the size of the label:

lblPhotoField.setIcon(new ImageIcon(ScaledImage(icon, lblPhotoField.getWidth(), lblPhotoField.getHeight()));

But I need the "icon" to be image , not imageicon as the method ScaledImage takes in Image parameter instead of ImageIcon.

 private Image ScaledImage(Image img, int w, int h){
    BufferedImage resizedImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = resizedImage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0,0,w,h,null);
    g2.dispose();
    return resizedImage;
}

Yup I did tried changing the return value to ImageIcon but it gave me errors. So I'm now focusing on how to convert ImageIcon to Image so I can put it in the method line, getting the icon and set my label it like this:

 lblPhotoField.setIcon(icon);

Use the ImageIcon#getImage method...

ScaledImage(icon.getImage(), lblPhotoField.getWidth(), lblPhotoField.getHeight())

Unless you are setting the size of the lblPhotoField you're self (which in of it self is worrisome) or it has already being laid out, I wouldn't rely on the getWidth() and getHeight()

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