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
Post a Comment