extending BufferedImage

后端 未结 2 2058
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 14:32

Why does the following code show a black image instead of the picture? How to properly extend BufferedImage?

class SizeOfImage {

    public static void main(Str         


        
相关标签:
2条回答
  • 2021-01-22 15:10

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-22 15:35

    Probably because the downloaded image bi is never drawn onto the cstImg.

    This line:

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

    creates a new image based on the width, height and type of bi... not the content of bi. For that you probably want to do something like

    cstImg.getGraphics().drawImage(bi, 0, 0, null);
    
    0 讨论(0)
提交回复
热议问题