2012-12-17 43 views
1

當我在畫布上繪製圖像時,圖像周圍的白色像素也與圖像邊界相關。有關如何防止這種情況的任何提示?我想加載一個沒有額外白色像素的圖像。我該怎麼做呢?

+1

您需要繪製透明圖像:http://stackoverflow.com/questions/8272583/drawing-transparent-images-in-java-graphics2d – zebediah49

+0

我讀了,我仍然困惑xx – Tikitaco

+0

如果圖像一開始不透明,您可以對其進行過濾,使白色像素變爲透明,但這也會發生在內部白色像素的情況下,因此必須小心操作。 –

回答

1

enter image description here

import java.awt.*; 
import java.awt.image.BufferedImage; 
import javax.swing.*; 
import javax.imageio.ImageIO; 
import java.net.URL; 

class ImageTransparencyByColor { 

    public static BufferedImage getTransparentImage(
     BufferedImage image, Color transparent) { 
     // must have a transparent image 
     BufferedImage img = new BufferedImage(
      image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB); 
     Graphics2D g= img.createGraphics(); 
     for (int x=0; x<img.getWidth(); x++) { 
      for (int y=0; y<img.getHeight(); y++) { 
       if (image.getRGB(x,y)!=transparent.getRGB()) { 
        img.setRGB(x,y, image.getRGB(x,y)); 
       } 
      } 
     } 
     g.dispose(); 
     return img; 
    } 

    public static void main(String[] args) throws Exception { 
     URL url = new URL ("http://www.gravatar.com/avatar" + 
      "/ab5193916ccf152f96b0a69323e934a1?s=128&d=identicon&r=PG"); 
     final BufferedImage trans = getTransparentImage(
      ImageIO.read(url), Color.WHITE); 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       JLabel gui = new JLabel(new ImageIcon(trans)); 
       JOptionPane.showMessageDialog(null, gui); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 
+0

完美工作。謝謝! – Tikitaco

0

使用.png圖片。一個.gif圖片只有全部/沒有transpancy。

+0

我正在使用一個.png圖像。 – Tikitaco

0

將您的圖像插入到JPanel中。帆布是一個重量級的組件。或者,嘗試更改畫布的Alpha。 this.setBackground(new Color(0,0,0,0);

編輯:試試這個。爲你的圖像創建一個類。您初始化圖像的方式並不重要。

public class MyImage extends JPanel { 

    private final URL IMG_DIRECTORY = Main.class.getResource("/res/yourImage.png"); // Image directory 

    public MyImage() { 

     try { 
      img = ImageIO.read(IMG_DIRECTORY); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     this.setSize(img.getWidth(null), img.getHeight(null); 

    } 

    @Override 
    public void paint(Graphics g) { 

     g.drawImage(img, 0, 0, null); 

    } 

在你的框架類中,聲明你的形象類MyImage yourImage = new MyImage();,然後將其添加到任何你的contentPane了。

+0

如果我的2個答案中的任何一個都沒有幫助你,請發佈你的SSCCE –

+0

im正在加載的圖片覆蓋了一系列不同的彩色背景,所以我需要白色像素透明以某種方式... – Tikitaco

+0

答案編輯.. –

相關問題