简体   繁体   English

使用jlabel上的imageicon自动调整图像大小

[英]Autoresize the image using imageicon on jlabel

I need to fit the image on jlabel, my images are stored in MySql table and I getting those using following code - 我需要将图像放置在jlabel上,我的图像存储在MySql表中,并使用以下代码获取这些图像-

byte[] imagedata=rs.getBytes(6); // rs is ResultSet of table
format=new ImageIcon(imagedata);
jLabel15.setIcon(format);

How can I resize the "format" which I want to display on jLabel15. 如何调整要在jLabel15上显示的“格式”的大小。

Edited: Image column in table is bigblob data type 编辑:表中的图像列是bigblob数据类型

you can scale your image the following way, 您可以按照以下方式缩放图像,

    Image img = format.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);
    jLabel15.setIcon(new ImageIcon(img));

I have scalled the image to 50X50 you can scale it to your desired size 我将图片缩放为50X50,您可以将其缩放到所需的尺寸

Here is an example how to resize the image on resize of the component. 这是一个如何根据组件的大小调整图像大小的示例。

import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.net.URL;

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

public class ResizedLabelTest {

    public static void main(String[] args) throws Exception {
        JFrame frm = new JFrame("ResizedLabel test");
        URL url = new URL("http://i.stack.imgur.com/37IMZ.jpg?s=128&g=1");
        final ImageIcon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        label.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                JLabel label = (JLabel) e.getComponent();
                Dimension size = label.getSize();
                Image resized = icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH);
                label.setIcon(new ImageIcon(resized));
            }
        });
        frm.add(label);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.pack();
        frm.setVisible(true);
    }
}

我想的一种方法是重写ImageIcon的paintIcon(...)方法,如果调整了图标本身的大小,则可以调整图像的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM