【问题标题】:extending BufferedImage扩展 BufferedImage
【发布时间】:2012-01-03 03:05:39
【问题描述】:

为什么下面的代码显示的是黑色图像而不是图片?如何正确扩展 BufferedImage?

class SizeOfImage {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://cloudbite.co.uk/wp-content/uploads/2011/03/google-chrome-logo-v1.jpg");
        final BufferedImage bi = ImageIO.read(url);
        final String size = bi.getWidth() + "x" + bi.getHeight();

        final  CustomImg cstImg = new CustomImg(bi.getWidth(), bi.getHeight(), bi.getType());

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JLabel l = new JLabel(size, new ImageIcon(cstImg), SwingConstants.RIGHT);
                JOptionPane.showMessageDialog(null, l);
            }
        });
    }

    public static class CustomImg extends BufferedImage {

        public CustomImg(int width, int height, int type){
            super(width, height, type);
        }

    }
}

【问题讨论】:

  • “如何正确扩展BufferedImage?” 为什么需要扩展呢?不要误会我的意思,在某些神秘的情况下你可以扩展它,但请幽默。编辑:我刚刚注意到代码既没有扩展 BI,也没有绘制到第二个 BI。
  • 因为我需要一个自定义类扩展缓冲图像上面的代码只是一个例子
  • @AndrewThompson '为什么需要扩展它? - OP:'因为我需要一个自定义类来扩展它'......这不是原因,只是重复:-) 请回答“为什么”,这很关键

标签: java image swing jlabel bufferedimage


【解决方案1】:

import java.awt.image.BufferedImage;
import java.awt.Graphics;
import javax.swing.*;
import javax.imageio.ImageIO;

import java.net.URL;

class SizeOfImage {

    public static void main(String[] args) throws Exception {
        URL url = new URL(
            "http://cloudbite.co.uk/wp-content/" +
            "uploads/2011/03/google-chrome-logo-v1.jpg");
        BufferedImage bi = ImageIO.read(url);
        final String size = bi.getWidth() + "x" + bi.getHeight();
        final  CustomImg cstImg = new CustomImg(
            bi.getWidth(),
            bi.getHeight(), bi.
            getType());

        // paint something to the new image!
        Graphics g = cstImg.createGraphics();
        g.drawImage(bi,0,0,null);
        g.dispose();

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JLabel l = new JLabel(
                    size,
                    new ImageIcon(cstImg),
                    SwingConstants.RIGHT );
                JOptionPane.showMessageDialog(null, l);
            }
        });
    }

    public static class CustomImg extends BufferedImage {
        public CustomImg(int width, int height, int type){
            super(width, height, type);
        }
    }
}

【讨论】:

  • +1 简洁。另请参阅thread
【解决方案2】:

可能是因为下载的图像bi 从未绘制到cstImg 上。

这一行:

CustomImg cstImg = new CustomImg(bi.getWidth(), bi.getHeight(), bi.getType());

根据bi... 的宽度、高度和类型创建一个新图像,而不是bi 的内容。为此,您可能想做类似的事情

cstImg.getGraphics().drawImage(bi, 0, 0, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-11
    • 2015-12-23
    • 2019-02-25
    • 2020-09-10
    • 2014-09-23
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多