您應該看看RGBA color model。
在這個模型中,A代表alpha通道,它通常用作不透明通道。
這意味着你可以通過你的顏色的Alpha值設置爲0
的java.awt.Color類提供了一些構造函數,你可以指定一種顏色的Alpha值,例如有一個「透明」顏色:
顏色(INT R,INT克,INT b,INT a)創建的sRGB顏色與指定的紅色,綠色,藍色的 ,和α的值在範圍(0 - 255)。
如果你找不到一個給你這個選項的程序,你可以讓你的圖像的背景顏色透明。
例如,我寫的這段代碼試圖從「灰色背景上的白色國王」圖像中刪除背景顏色。 如果您嘗試編譯並運行,你應該得到這樣的結果:
正如你所看到的不是所有的背景已經從圖像中刪除,這是由於這樣的事實的背景是由由不同的顏色。
但是這個例子說明你可以操縱你的圖像像素以獲得透明度。
我認爲最好的選擇是在網上搜索一些已經有透明背景的國際象棋圖像。
例如,我可以在這裏發佈一些鏈接(我不知道是否有一些版權問題,照顧這個),你可以很容易地得到所有的圖片,如果你檢查的網址:
Black Rook
White Queen
示例代碼:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TransparentTest
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
BufferedImage image = ImageIO.read(new File("KING.jpg"));
BufferedImage transparentImage = removeColors(image,new Color(245,222,180));
createAndShowGUI(image,transparentImage);
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null,"Please check your file image path","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
}
public static void createAndShowGUI(BufferedImage image,BufferedImage transparentImage) {
JPanel pane = new JPanel(new FlowLayout(FlowLayout.CENTER,40,10));
pane.setBackground(Color.BLUE);
pane.add(new JLabel(new ImageIcon(image)));
pane.add(new JLabel(new ImageIcon(transparentImage)));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static BufferedImage removeColors(BufferedImage image,Color... colorsBlackList) throws IOException {
int height = image.getHeight(), width=image.getWidth();
BufferedImage transparentImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
for(int y=0;y<height;y++) {
for(int x=0;x<width;x++) {
int pixel = image.getRGB(x,y);
int red = (pixel>>16) &0xff;
int green = (pixel>>8) &0xff;
int blue = (pixel>>0) &0xff;
int alpha = 255;
// Settings opacity to 0 ("transparent color") if the pixel color is equal to a color taken from the "blacklist"
for(Color color : colorsBlackList) {
if(color.getRGB() == pixel) alpha = 0;
}
transparentImage.setRGB(x,y,(alpha&0x0ff)<<24 | red<<16 | green<<8 | blue);
}
}
return transparentImage;
}
}
你爲什麼不使您的圖片的背景中paint.net透明? – eldo
不幸的是,如果我從paint.net中的片段圖像中刪除背景(所以只有它自己保留的部分,其餘部分只是黑色和白色方塊),然後將它作爲ImageIcon在按鈕上進行加載,它將具有白色背景透明 – Fredegar
@eldo概述了最佳方法。在專用的繪畫應用程序中將純色BG更改爲透明。 *「是否有一些顏色可以自動變爲透明」*否。另請參閱[製作強大的可調整大小的Swing Chess GUI](http://stackoverflow.com/q/21142686/418556),以獲取獲取圖標的不同方法棋子(在運行時產生它們)。 –