自动缩放 ImageIcon 以适应标签大小

2024-01-04

在我的 JFrame 上,我使用以下代码在面板上显示图像:

  ImageIcon img= new ImageIcon("res.png");
  jLabel.setIcon(img);

我想“自动调整”标签中图片的大小。事实上,有时图像大小只有几个像素,有时甚至更多。

有没有办法设置标签的大小,然后自动调整标签中图像的大小?


这是一个棘手的问题。您强调了您正在使用的事实JLabel展示图像,这是做事的标准方式,但是,JLabel是一个复杂的小野兽,具有文本、图标和文本对齐和定位。

如果您不需要所有额外的功能,我只需为自己创建一个能够绘制缩放图像的自定义组件......

下一个问题是,你想如何缩放图像?您想保持图像的纵横比吗?您想要将图像“适合”或“填充”到可用空间吗?

@大卫是对的。您应该尽可能避免Image#getScaledInstance因为它不是最快的,但更重要的是,一般来说,它也不提供最高的质量。

适合与填充

下面的示例相当简单(并且大量借用了我的代码库,因此可能也有点复杂;))。它可以从后台缩放线程使用,但我会根据原始图像的潜在大小做出决定。

public class ResizableImage {

    public static void main(String[] args) {
        new ResizableImage();
    }

    public ResizableImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                try {
                    BufferedImage image = ImageIO.read(new File("/path/to/your/image"));

                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new ScalablePane(image));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class ScalablePane extends JPanel {

        private Image master;
        private boolean toFit;
        private Image scaled;

        public ScalablePane(Image master) {
            this(master, true);
        }

        public ScalablePane(Image master, boolean toFit) {
            this.master = master;
            setToFit(toFit);
        }

        @Override
        public Dimension getPreferredSize() {
            return master == null ? super.getPreferredSize() : new Dimension(master.getWidth(this), master.getHeight(this));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Image toDraw = null;
            if (scaled != null) {
                toDraw = scaled;
            } else if (master != null) {
                toDraw = master;
            }

            if (toDraw != null) {
                int x = (getWidth() - toDraw.getWidth(this)) / 2;
                int y = (getHeight() - toDraw.getHeight(this)) / 2;
                g.drawImage(toDraw, x, y, this);
            }
        }

        @Override
        public void invalidate() {
            generateScaledInstance();
            super.invalidate();
        }

        public boolean isToFit() {
            return toFit;
        }

        public void setToFit(boolean value) {
            if (value != toFit) {
                toFit = value;
                invalidate();
            }
        }

        protected void generateScaledInstance() {
            scaled = null;
            if (isToFit()) {
                scaled = getScaledInstanceToFit(master, getSize());
            } else {
                scaled = getScaledInstanceToFill(master, getSize());
            }
        }

        protected BufferedImage toBufferedImage(Image master) {
            Dimension masterSize = new Dimension(master.getWidth(this), master.getHeight(this));
            BufferedImage image = createCompatibleImage(masterSize);
            Graphics2D g2d = image.createGraphics();
            g2d.drawImage(master, 0, 0, this);
            g2d.dispose();
            return image;
        }

        public Image getScaledInstanceToFit(Image master, Dimension size) {
            Dimension masterSize = new Dimension(master.getWidth(this), master.getHeight(this));
            return getScaledInstance(
                            toBufferedImage(master),
                            getScaleFactorToFit(masterSize, size),
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR,
                            true);
        }

        public Image getScaledInstanceToFill(Image master, Dimension size) {
            Dimension masterSize = new Dimension(master.getWidth(this), master.getHeight(this));
            return getScaledInstance(
                            toBufferedImage(master),
                            getScaleFactorToFill(masterSize, size),
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR,
                            true);
        }

        public Dimension getSizeToFit(Dimension original, Dimension toFit) {
            double factor = getScaleFactorToFit(original, toFit);
            Dimension size = new Dimension(original);
            size.width *= factor;
            size.height *= factor;
            return size;
        }

        public Dimension getSizeToFill(Dimension original, Dimension toFit) {
            double factor = getScaleFactorToFill(original, toFit);
            Dimension size = new Dimension(original);
            size.width *= factor;
            size.height *= factor;
            return size;
        }

        public double getScaleFactor(int iMasterSize, int iTargetSize) {
            return (double) iTargetSize / (double) iMasterSize;
        }

        public double getScaleFactorToFit(Dimension original, Dimension toFit) {
            double dScale = 1d;
            if (original != null && toFit != null) {
                double dScaleWidth = getScaleFactor(original.width, toFit.width);
                double dScaleHeight = getScaleFactor(original.height, toFit.height);
                dScale = Math.min(dScaleHeight, dScaleWidth);
            }
            return dScale;
        }

        public double getScaleFactorToFill(Dimension masterSize, Dimension targetSize) {
            double dScaleWidth = getScaleFactor(masterSize.width, targetSize.width);
            double dScaleHeight = getScaleFactor(masterSize.height, targetSize.height);

            return Math.max(dScaleHeight, dScaleWidth);
        }

        public BufferedImage createCompatibleImage(Dimension size) {
            return createCompatibleImage(size.width, size.height);
        }

        public BufferedImage createCompatibleImage(int width, int height) {
            GraphicsConfiguration gc = getGraphicsConfiguration();
            if (gc == null) {
                gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
            }

            BufferedImage image = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            image.coerceData(true);
            return image;
        }

        protected BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor, Object hint, boolean bHighQuality) {
            BufferedImage imgScale = img;
            int iImageWidth = (int) Math.round(img.getWidth() * dScaleFactor);
            int iImageHeight = (int) Math.round(img.getHeight() * dScaleFactor);

            if (dScaleFactor <= 1.0d) {
                imgScale = getScaledDownInstance(img, iImageWidth, iImageHeight, hint, bHighQuality);
            } else {
                imgScale = getScaledUpInstance(img, iImageWidth, iImageHeight, hint, bHighQuality);
            }

            return imgScale;
        }

        protected BufferedImage getScaledDownInstance(BufferedImage img,
                        int targetWidth,
                        int targetHeight,
                        Object hint,
                        boolean higherQuality) {

            int type = (img.getTransparency() == Transparency.OPAQUE)
                            ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;

            if (targetHeight > 0 || targetWidth > 0) {
                int w, h;
                if (higherQuality) {
                    // Use multi-step technique: start with original size, then
                    // scale down in multiple passes with drawImage()
                    // until the target size is reached
                    w = img.getWidth();
                    h = img.getHeight();
                } else {
                    // Use one-step technique: scale directly from original
                    // size to target size with a single drawImage() call
                    w = targetWidth;
                    h = targetHeight;
                }

                do {
                    if (higherQuality && w > targetWidth) {
                        w /= 2;
                        if (w < targetWidth) {
                            w = targetWidth;
                        }
                    }
                    if (higherQuality && h > targetHeight) {
                        h /= 2;
                        if (h < targetHeight) {
                            h = targetHeight;
                        }
                    }

                    BufferedImage tmp = new BufferedImage(Math.max(w, 1), Math.max(h, 1), type);
                    Graphics2D g2 = tmp.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                    g2.drawImage(ret, 0, 0, w, h, null);
                    g2.dispose();

                    ret = tmp;
                } while (w != targetWidth || h != targetHeight);
            } else {
                ret = new BufferedImage(1, 1, type);
            }

            return ret;
        }

        protected BufferedImage getScaledUpInstance(BufferedImage img,
                        int targetWidth,
                        int targetHeight,
                        Object hint,
                        boolean higherQuality) {

            int type = BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;
            int w, h;
            if (higherQuality) {
                // Use multi-step technique: start with original size, then
                // scale down in multiple passes with drawImage()
                // until the target size is reached
                w = img.getWidth();
                h = img.getHeight();
            } else {
                // Use one-step technique: scale directly from original
                // size to target size with a single drawImage() call
                w = targetWidth;
                h = targetHeight;
            }

            do {
                if (higherQuality && w < targetWidth) {
                    w *= 2;
                    if (w > targetWidth) {
                        w = targetWidth;
                    }
                }

                if (higherQuality && h < targetHeight) {
                    h *= 2;
                    if (h > targetHeight) {
                        h = targetHeight;
                    }
                }

                BufferedImage tmp = new BufferedImage(w, h, type);
                Graphics2D g2 = tmp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                g2.drawImage(ret, 0, 0, w, h, null);
                g2.dispose();

                ret = tmp;
                tmp = null;
            } while (w != targetWidth || h != targetHeight);
            return ret;
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动缩放 ImageIcon 以适应标签大小 的相关文章

随机推荐

  • Oracle 将行转为列[重复]

    这个问题在这里已经有答案了 我有以下表格 TABLE1 id name 1 n1 2 n2 TABLE2 id tipo valor 1 t1 v1 1 t2 v2 2 t1 v1 2 t2 v5 2 t3 v3 我试图得到 id name
  • 如何在 Django JSONField 中过滤 JSON 数组

    我对在 Django 2 0 3 中过滤 postgres JSONField 感到疯狂 json 以数组形式存储 例如 tasks task test level 10 task test 123 level 20 我尝试过的 myMod
  • grails图像绝对路径

    我的标题模板中有这张图片 img src images slide 1 jpg alt width 175 height 77 当从 main 目录内的 gsp 文件使用模板时 将加载图像 不过 如果我在控制器内的 gsp 文件中使用相同的
  • ProcessBuilder调试

    我创建了一个可执行 jar 并使用另一个 java 程序的进程构建器执行它 这是我的代码 public class SomeClass public static void main String args Process p null P
  • VB.NET 相当于 C# 的 using 指令

    我正在将一些代码从 C 转换为 VB NET 并且我需要知道 C 的 using 指令的等效项是什么 Update 抱歉 但到目前为止我还没有得到答案 这是一个 C 示例 using moOutlook Microsoft Office I
  • 在 .NET MVC4 中调用本地 Web 服务时出现 HTTP 404 错误

    我正在尝试学习 NET mvc4 中的 Web 服务 我尝试创建一个新的 Internet 应用程序并向该项目添加一个 Web 服务 asmx 默认情况下 VS 添加一个 HelloWorld Web 服务 当我尝试在浏览器中运行它时 我确
  • jasmine需要sinon.js吗?

    我在网上看到过人们使用的例子jasmine http pivotal github com jasmine 和 一起sinon http sinonjs org 然而 茉莉支持间谍 据我所知 诗乃就是这么做的 那么问题来了 诗浓在使用茉莉花
  • 由于 COMMAND_LINE_LOGGING_LEVEL 原因,无法导入 Markdown

    我遇到了一个奇怪的错误 我可以在 Python 中导入 markdown 并且可以在 Django runserver 内的 python 中导入 markdown 但是当尝试在 Gunicorn 的应用程序服务器内导入 markdown
  • 找不到网络浏览器:无法找到可运行的浏览器。 Jupyter笔记本

    Jupyter notebook 无法打开网络浏览器 之前用的好好的 后来windows 10提示更新后就开始在Microsoft Edge中打开了 当我尝试将其更改为默认浏览器 chrome 时 它根本无法打开 我跟着如何在 Window
  • 用于 Excel 克隆的正确数据结构

    假设我正在使用 C 开发 Excel 克隆 我的网格表示如下 private struct CellValue private int column private int row private string text private L
  • 如何卸载 Perl 模块?

    我在我的 Linux 机器上安装了一些 Perl 模块 如果我输入perldoc perllocal它显示了我的机器中安装的 Perl 模块的列表 但现在我不需要这些 Perl 模块 所以我想删除它们 有谁知道如何卸载或删除Linux de
  • PHP - 比较两个多维数组

    我有两个包含数据的数组 我需要比较这两个数组并创建一个最终数组 这是我的情况 grab a list of the folders folders glob GLOB ONLYDIR create empty array s which w
  • 重试 Visual Studio C# 测试方法

    我很好奇是否有任何内置机制可以retry在 Visual Studio 2008 C 单元测试框架中进行测试 举个例子 我有一个 C 单元测试 如下所示 TestMethod public void MyMethod DoSomething
  • 从一个 dagger 2 模块如何访问另一个 dagger 2 模块中提供的 SharedPreferences

    从一个 dagger2 模块提供 SharedPreferences 后 在另一个 dagger2 模块中想要使用它 怎么做 下面的代码似乎不起作用 组件 Singleton Component modules arrayOf DataMa
  • Redis 6 可以利用多核 CPU 的优势吗?

    Since Redis 6支持多线程IO https redislabs com blog diving into redis 6 在超过2个核心的机器上部署Redis有意义吗 它是否能够利用额外的核心 或者 2 个核心仍然是理想的选择 一
  • 计算阿克曼函数的较大值

    我有一些代码 int CalculateAckermann int x int y if x return y if y return CalculateAckermann x 1 else return CalculateAckerman
  • 返回 Fortran 中不同长度的字符串数组

    我想创建一个类型来包含 Fortran 中的字符串数组 而无需显式分配长度 以便我可以从函数返回它 以下是我的类型 type returnArr Character dimension 4 array end type returnArr
  • 由于 JSON 中转义的单引号,jQuery.parseJSON 抛出“无效 JSON”错误

    我正在使用以下方式向我的服务器发出请求jQuery post 我的服务器正在返回 JSON 对象 例如 var value 但是 如果任何值包含单引号 正确转义 如 jQuery 无法解析有效的 JSON 字符串 这是我的意思的一个例子 在
  • Numpy 每行动态切片

    如何在不使用 for 循环的情况下动态地对给定开始和结束索引的每一行进行切片 我可以使用下面列出的循环来完成此操作 但是对于 x shape 0 gt 1 mill 的情况来说 它太慢了 x np arange 0 100 x x resh
  • 自动缩放 ImageIcon 以适应标签大小

    在我的 JFrame 上 我使用以下代码在面板上显示图像 ImageIcon img new ImageIcon res png jLabel setIcon img 我想 自动调整 标签中图片的大小 事实上 有时图像大小只有几个像素 有时