Как изменить размер imageicon java

I'm making a Java Swing application that has the following layout (MigLayout): [icon][icon][icon][....] where icon = jlabel and the user can add more icons When the user adds or removes icons, the

I’m making a Java Swing application that has the following layout (MigLayout):

[icon][icon][icon][....]
where icon = jlabel and the user can add more icons

When the user adds or removes icons, the others should shrink or grow.

My question is really straightforward: I have a JLabel which contains an ImageIcon; how can I resize this icon?

Mr. Polywhirl's user avatar

Mr. Polywhirl

38.5k12 gold badges82 silver badges128 bronze badges

asked Jul 15, 2011 at 23:02

Marcos Roriz Junior's user avatar

1

Try this :

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);  // transform it back

(found it here)

answered Aug 20, 2013 at 12:46

trolologuy's user avatar

0

Resizing the icon is not straightforward. You need to use Java’s graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

Mr. Polywhirl's user avatar

Mr. Polywhirl

38.5k12 gold badges82 silver badges128 bronze badges

answered Jul 16, 2011 at 0:04

Suken Shah's user avatar

Suken ShahSuken Shah

1,59413 silver badges20 bronze badges

0

And what about it?:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

From: Resize a picture to fit a JLabel

answered Oct 1, 2015 at 11:12

tirz's user avatar

tirztirz

2,0031 gold badge21 silver badges36 bronze badges

This will keep the right aspect ratio.

    public ImageIcon scaleImage(ImageIcon icon, int w, int h)
    {
        int nw = icon.getIconWidth();
        int nh = icon.getIconHeight();

        if(icon.getIconWidth() > w)
        {
          nw = w;
          nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
        }

        if(nh > h)
        {
          nh = h;
          nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
        }

        return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
    }

Unmitigated's user avatar

Unmitigated

57.3k7 gold badges53 silver badges71 bronze badges

answered Dec 9, 2015 at 21:44

Kyle Phillips's user avatar

One (quick & dirty) way to resize images it to use HTML & specify the new size in the image element. This even works for animated images with transparency.

answered Jul 16, 2011 at 14:32

Andrew Thompson's user avatar

Andrew ThompsonAndrew Thompson

168k40 gold badges215 silver badges430 bronze badges

I agree this code works, to size an ImageIcon from a file for display while keeping the aspect ratio I have used the below.

/*
 * source File of image, maxHeight pixels of height available, maxWidth pixels of width available
 * @return an ImageIcon for adding to a label
 */


public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
{
    int newHeight = 0, newWidth = 0;        // Variables for the new height and width
    int priorHeight = 0, priorWidth = 0;
    BufferedImage image = null;
    ImageIcon sizeImage;

    try {
            image = ImageIO.read(source);        // get the image
    } catch (Exception e) {

            e.printStackTrace();
            System.out.println("Picture upload attempted & failed");
    }

    sizeImage = new ImageIcon(image);

    if(sizeImage != null)
    {
        priorHeight = sizeImage.getIconHeight(); 
        priorWidth = sizeImage.getIconWidth();
    }

    // Calculate the correct new height and width
    if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
    {
        newHeight = maxHeight;
        newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
    }
    else 
    {
        newWidth = maxWidth;
        newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
    }


    // Resize the image

    // 1. Create a new Buffered Image and Graphic2D object
    BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();

    // 2. Use the Graphic object to draw a new image to the image in the buffer
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(image, 0, 0, newWidth, newHeight, null);
    g2.dispose();

    // 3. Convert the buffered image into an ImageIcon for return
    return (new ImageIcon(resizedImg));
}

answered Dec 28, 2012 at 10:30

Adam's user avatar

I found that there is a minor edit to this fix from trolologuy on the last line of code, you will need to implement a new ImageIcon to get the code to compile properly (Yes I know this is 10 years ago). I found this to be an easy fix for a one off issue, but Suken Shah and Mr. Polywhirl have a better fix overall.

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // assign image to a new ImageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it smoothly  
ImageIcon newImageIcon = new ImageIcon(newimg);  // assign to a new ImageIcon instance

answered Nov 2, 2021 at 10:18

IRKillRoy's user avatar


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Daniel Searson wrote:Ok, here’s one way of doing it.

You load your image straight into the ImageIcon using the constructor that takes a file name as an argument like:

ImageIcon icon = new ImageIcon(«whatever.jpg»);

Make sure the reference you create is an ImageIcon reference. Then use getImage() to grab the image from the ImageIcon:

Image img = icon.getImage();

Now create a buffered image the same size as the image:

BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

Then blit the icon image to the buffered image, and resize it as you do so:

Graphics g = bi.createGraphics();

g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);

(The code above may be incorrect — check the docs)

Now recreate the IconImage with the new buffered image:

IconImage newIcon = new IconImage(bi);

Hope that helps.

— Daniel

I like this option. All of the posts I have read elsewhere recommend using the BufferedImage/Graphics.drawImage approach.

In this situation, it looks like you do actually need a resized image. In the project I am working on, I have been using a modified JLabel to use a resized icon. You may not need the whole IconLabel class, but it does implement the resize technique mentioned above. 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 http://stackoverflow.com/questions/10245220/java-image-resize-maintain-aspect-ratio). That way, you can pre-determine how big of a space you want your image to take without compromising its aspect ratio. 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.

In this JLabel-extending class, the real tricks are to override getPreferredSize and the paintComponent methods, where I do the image resizing.

мда, эта задачка посложней будет ..

Задать размер нельзя никак.
Можно создать копию Image_а с новыми размерами.

Есть две проблемы:
1. получить картинку
2. resize_нуть её

Первую я решил таким вот образом:

Код: Выделить всё

		URL imageURL = getClass().getResource("/test.jpg");
		ImageIcon imageIcon = new ImageIcon(imageURL);
		Image image = imageIcon.getImage();
		ToolkitImage toolkitImage = (ToolkitImage)image;
		BufferedImage bufferedImage = toolkitImage.getBufferedImage();

Наверное стоило бы проверять прямое кастование типов, но ну его
(не знаю, что делать, если картинка в иконке НЕ sun.awt.image.ToolkitImage ..)

и вторая — нашел где-то на SUNовском форуме:

Код: Выделить всё

	public static BufferedImage resizeImage(BufferedImage image, int width, int height) {
		
		ColorModel cm = image.getColorModel();
		
	    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
	    
	    boolean isRasterPremultiplied = cm.isAlphaPremultiplied();
	    
	    BufferedImage target = new BufferedImage(cm, raster, isRasterPremultiplied, null);
	    Graphics2D g2 = target.createGraphics();
	    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
	    
	    double scalex = (double) target.getWidth()/ image.getWidth();
	    double scaley = (double) target.getHeight()/ image.getHeight();
	    
	    AffineTransform xform = AffineTransform.getScaleInstance(scalex, scaley);
	    g2.drawRenderedImage(image, xform);
	    g2.dispose();
	    return target;
	}

Ну, в общем, у меня работает.
Вот полный код:

Код: Выделить всё

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import sun.awt.image.ToolkitImage;

public class ChangeIconSize {

	public ChangeIconSize() {
		
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		
		init(panel);
		
		frame.add(panel);
		
		frame.setSize(800, 600);
		frame.setVisible(true);
		
	}
	
	private void init(JPanel panel) {
				
		URL imageURL = getClass().getResource("/test.jpg");
		
		ImageIcon imageIcon = new ImageIcon(imageURL);
		
		JLabel l1 = new JLabel(imageIcon);
		l1.setBounds(0, 0, 400, 300);
		panel.add(l1);
		
		Image image = imageIcon.getImage();
		ToolkitImage toolkitImage = (ToolkitImage)image;
		BufferedImage bufferedImage = toolkitImage.getBufferedImage();		
		BufferedImage resizedImage = resizeImage(bufferedImage, bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
		
		ImageIcon imageIcon2 = new ImageIcon(resizedImage);
		
		JLabel l2 = new JLabel(imageIcon2);
		l2.setBounds(400, 0, 400, 300);
		panel.add(l2);
		
	}
	
	public static BufferedImage resizeImage(BufferedImage image, int width, int height) {
		
		ColorModel cm = image.getColorModel();
		
	    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
	    
	    boolean isRasterPremultiplied = cm.isAlphaPremultiplied();
	    
	    BufferedImage target = new BufferedImage(cm, raster, isRasterPremultiplied, null);
	    Graphics2D g2 = target.createGraphics();
	    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
	    
	    double scalex = (double) target.getWidth()/ image.getWidth();
	    double scaley = (double) target.getHeight()/ image.getHeight();
	    
	    AffineTransform xform = AffineTransform.getScaleInstance(scalex, scaley);
	    g2.drawRenderedImage(image, xform);
	    g2.dispose();
	    return target;
	}
	
	public static void main(String[] args) {
		new ChangeIconSize();
	}

}

I`m currently making an application to manage other application on windows.

when i resize the icon it change quality

i`m getting icon by this code

ShellFolder shell = ShellFolder.getShellFolder(new File(load1.getString("Path")));
image = shell.getIcon(true);

And when i resize it it change the quality.
My resize code is

sIMG = image.getScaledInstance(45, 45, Image.SCALE_AREA_AVERAGING);

What i want to do to keep the quality of the icon.

Please help.

asked May 19, 2014 at 16:28

Shansl95's user avatar

2

I’m assuming you want to re-size your icon to look the same no matter what size you change it to. Regular images will are composed of pixels therefore lost of quality is inevitable.

When I did a web design project at my school I learned about Vector images(.svg).
Summary Of Vector Vs Bitmap http://etc.usf.edu/techease/win/images/what-is-the-difference-between-bitmap-and-vector-images/

Of course anyone please correct me if I’m wrong but I think vectors is the only way you can achieve your goal assuming that I’m understanding your question. Vector image quality does not change much or at all on re-size.

Java doesn’t natively support Vector Images but follow this tutorial and you should achieve your goal. (It’s not really a tutorial more like copy and paste)

http://plindenbaum.blogspot.com/2009/07/simple-java-based-svg-renderer.html

Also this link will let you convert your existing images to SVG

http://vectormagic.com/home

(you get 2 downloads when you sign up) There are other tools to convert to SVG but this was the quickest solution I could find. If you’re good with Photoshop I think I saw some tutorials for it but don’t quote me on that.
I hope this is what you were looking for best of luck to.

answered May 19, 2014 at 17:17

Paul Brunache's user avatar

3

you can resize any image by the following code.

$thumb = new Imagick();
$thumb->readImage('myimage.gif');    $thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->clear();
$thumb->destroy(); 

For more information please go to the following link.

resize image

resize optimized image

answered May 19, 2014 at 16:57

quicksoft's user avatar

2

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер gpt раздела
  • Как изменить размер gpt диска
  • Как изменить размер gif файла
  • Как изменить размер flex элемента
  • Как изменить размер favicon

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии