2011-11-21 106 views
1

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

    } 
} 
+8

*“如何正确扩展的BufferedImage?” *为什么你需要扩展它?不要误会我的意思,你可能会在这种情况下扩展它,但是幽默我。编辑:我只是注意到,代码既不扩展BI,也没有绘制到第二个BI。 –

+0

因为我需要一个自定义类来扩展缓冲图像,所以上面的代码只是一个例子 – Radek

+1

@AndrewThompson'你为什么需要扩展它? - OP:'因为我需要一个自定义的类来扩展它......'这不是一个原因,只是一个重复:-)请回答“为什么”,简洁的关键是 – kleopatra

回答

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

+1。另请参阅此[线索](http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/e74886dace754256)。 – trashgod

6

大概是因为下载的图像bi从未绘制到cstImg

这条线:

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

创建一个基于的bi的宽度,高度和类型...的bi不是内容的新形象。对于您可能想要做像

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