扩展BufferedImage [英] extending BufferedImage

查看:98
本文介绍了扩展BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the following code show a black image instead of the picture? How to properly extend 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);
        }

    }
}


推荐答案

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

这篇关于扩展BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆