by
149 11
2
6
2,640
2
Top 1% !
Popular
Famous
Easy-to-find
Specified
OpenSource
Popularity: 5128th place
Created
Modified Jul 25, 2014
InputName0srcImg
InputName1w
InputName2h
InputType0ImageIcon
InputType1int
InputType2int
Languagejava
LicenseMIT_X11
MethodNamegetScaledImage
OutputTypeImageIcon

Scale Image to fit dimensions

This snippet of code allows you to scale a image proportional such that it fits the provided dimensions.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/98795/Scale-Image-to-fit-dimensions?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
public static ImageIcon getScaledImage(ImageIcon srcImg, int w, int h){ int imgWidth = srcImg.getIconWidth(); int imgHeight = srcImg.getIconHeight(); //Find the right width if(imgWidth > w){ float sWidth = imgWidth-w; float sFactor = (sWidth/imgWidth); imgWidth = w; imgHeight = (int) (imgHeight-(imgHeight*sFactor)); } //Find the right hight if(imgHeight > h){ float sHeight = imgHeight-h; float sFactor = sHeight/imgHeight; imgHeight = h; imgWidth = (int) (imgWidth-(imgWidth*sFactor)); } BufferedImage resizedImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(srcImg.getImage(), 0, 0, imgWidth, imgHeight, null); g2.dispose(); return new ImageIcon(resizedImg); }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus