扩展BufferedImage

时间:2011-11-21 16:12:01

标签: java image swing jlabel bufferedimage

为什么以下代码显示的是黑色图片而不是图片?如何正确扩展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);
        }

    }
}

2 个答案:

答案 0 :(得分:6)

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

这一行:

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

根据bi的宽度,高度和类型创建新图片...而不是bi的内容。为此,你可能想做类似

的事情
cstImg.getGraphics().drawImage(bi, 0, 0, null);

答案 1 :(得分:6)

Size of Image

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