2014-03-30 22 views
0

好吧,所以我創建了一個方法,調整ImageIcon的大小我的問題是我怎樣稱呼它爲了使ImageIcon我想調整大小,在這裏感謝,和方法應該工作,因此任何人尋找一個不調整,你應該能夠使用它的方法:)哪裏/如何調用我的resizeimage方法

public static void resizeIcon(ImageIcon icon, int Width, int Height){ 
    Image geticon = icon.getImage(); 
    BufferedImage bi = new BufferedImage(geticon.getWidth(null), geticon.getHeight(null), BufferedImage.TYPE_INT_RGB); 
    Graphics g = bi.createGraphics(); 
    g.drawImage(geticon, 0, 0, Width, Height, null); 
    ImageIcon resizedicon = new ImageIcon(bi); 
    icon = resizedicon; 

} 

回答

0

您通過資源保存圖像大小。然後第一設置的ImageIcon作爲調整後的圖像。

public static Boolean resizeImage(String sourceImage, String destinationImage, Integer Width, Integer Height) { 
    BufferedImage origImage; 
    try { 

     origImage = ImageIO.read(new File(sourceImage)); 
     int type = origImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : origImage.getType(); 

     //*Special* if the width or height is 0 use image src dimensions 
     if (Width == 0) { 
      Width = origImage.getWidth(); 
     } 
     if (Height == 0) { 
      Height = origImage.getHeight(); 
     } 

     int fHeight = Height; 
     int fWidth = Width; 

     //Work out the resized width/height 
     if (origImage.getHeight() > Height || origImage.getWidth() > Width) { 
      fHeight = Height; 
      int wid = Width; 
      float sum = (float)origImage.getWidth()/(float)origImage.getHeight(); 
      fWidth = Math.round(fHeight * sum); 

      if (fWidth > wid) { 
       //rezise again for the width this time 
       fHeight = Math.round(wid/sum); 
       fWidth = wid; 
      } 
     } 

     BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type); 
     Graphics2D g = resizedImage.createGraphics(); 
     g.setComposite(AlphaComposite.Src); 

     g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
     g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
     g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

     g.drawImage(origImage, 0, 0, fWidth, fHeight, null); 
     g.dispose(); 

     ImageIO.write(resizedImage, "png", new File(destinationImage)); 

    } catch (IOException ex) { 
     System.out.println(""+ex); 
     return false; 
    } 

    return true; 
} 

然後調用

ImageIcon ico = new ImageIcon(destinationImage); 
labelforIcon.setIcon(ico); 
相關問題