Подтвердить что ты не робот

Как изменить размер JLabel ImageIcon?

Я создаю приложение Java Swing, которое имеет следующий макет (MigLayout):

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

Когда пользователь добавляет или удаляет значки, другие должны сокращаться или расти.

Мой вопрос очень прост: у меня есть JLabel, который содержит ImageIcon; как изменить размер значка?

4b9b3361

Ответ 1

Изменение размера значка не является простым. Для масштабирования изображения вам необходимо использовать графику 2D 2D. Первый параметр - это класс изображения, который можно легко получить из класса ImageIcon. Вы можете использовать класс ImageIcon для загрузки вашего файла изображения, а затем просто вызвать метод getter для получения изображения.

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;
}

Ответ 2

Попробуйте следующее:

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

(нашел здесь)

Ответ 4

Один (быстрый и грязный) способ изменить размер изображений для использования HTML и указать новый размер в элементе изображения. Это даже работает для анимированных изображений с прозрачностью.

Ответ 5

Я согласен, что этот код работает, чтобы размер ImageIcon из файла для отображения, сохраняя соотношение сторон, которое я использовал ниже.

/*
 * 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));
}

Ответ 6

Это сохранит правильное соотношение сторон.

    public ImageIcon scaleImage(ImageIcon the_icon, int the_w, int the_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));
    }