java - Resize a picture to fit a JLabel -


i'm trying make picture fit jlabel. wish reduce picture dimensions more appropriate swing jpanel.

i tried setpreferredsize doesn't work.

i'm wondering if there simple way it? should scale image purpose?

outline

here steps follow.

  • read picture bufferedimage.
  • resize bufferedimage bufferedimage that's size of jlabel.
  • create imageicon resized bufferedimage.

you not have set preferred size of jlabel. once you've scaled image size want, jlabel take size of imageicon.

read picture bufferedimage

bufferedimage img = null; try {     img = imageio.read(new file("strawberry.jpg")); } catch (ioexception e) {     e.printstacktrace(); } 

resize bufferedimage

image dimg = img.getscaledinstance(label.getwidth(), label.getheight(),         image.scale_smooth); 

make sure label width , height same proportions original image width , height. in other words, if picture 600 x 900 pixels, scale 100 x 150. otherwise, picture distorted.

create imageicon

imageicon imageicon = new imageicon(dimg); 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -