6/11/2023 0 Comments Image icon resize to panel java![]() Rescale the image such that it maintains its aspect ratio but fits within the IconLabel size Public IconLabel(Image image, int width, int height) Public IconLabel(ImageIcon icon, int width, int height) In this JLabel-extending class, the real tricks are to override getPreferredSize and the paintComponent methods, where I do the image resizing. The getScaledDimension is taken from that URL, and it does a better job of explaining how it resizes an image and maintains its aspect ratio. That way, you can pre-determine how big of a space you want your image to take without compromising its aspect ratio. For added bonus (and for satisfying my OCD), I have pieced together some logic that also scales the image to within a certain size, maintaining its aspect ratio (i.e., I used ). You may not need the whole IconLabel class, but it does implement the resize technique mentioned above. In the project I am working on, I have been using a modified JLabel to use a resized icon. In this situation, it looks like you do actually need a resized image. All of the posts I have read elsewhere recommend using the BufferedImage/Graphics.drawImage approach. Now recreate the IconImage with the new buffered image: (The code above may be incorrect - check the docs) G.drawImage(img, 0, 0, WIDTH, HEIGHT, null) Then blit the icon image to the buffered image, and resize it as you do so: Now create a buffered image the same size as the image:īufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB) Then use getImage() to grab the image from the ImageIcon: Make sure the reference you create is an ImageIcon reference. ![]() ![]() ImageIcon icon = new ImageIcon("whatever.jpg") You load your image straight into the ImageIcon using the constructor that takes a file name as an argument like: Daniel Searson wrote:Ok, here's one way of doing it. ![]()
0 Comments
Leave a Reply. |