http://www.cnblogs.com/dotjava/archive/2008/09/04/1283963.html
關於Java生成背景透明的png圖片
最近用到Java動態生成背景透明的圖片功能,從gif和png中選擇了png格式,箇中緣由就不說了,於是動手到網上搜索有用的代碼。現把搜索結果總結如下:
1. 生成png圖片
int width = 400;
int height = 300;
// 創建BufferedImage對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取Graphics2D
Graphics2D g2d = image.createGraphics();
// 畫圖
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(1));
g2d.draw
//釋放對象
g2d.dispose();
// 保存文件
ImageIO.write(image, "png", new File("c:/test.png"));
這只是繪製圖形的代碼,其背景是黑色的,如何才能背景透明呢?繼續搜索,沒有得到結果,不過搜出以下代碼,它只是把自己繪製的圖形設置爲透明或半透明,背景並不透明,如下:
2. 繪製半透明圖形
int width = 400;
int height = 300;
// 創建BufferedImage對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取Graphics2D
Graphics2D g2d = image.createGraphics();
// 設置透明度
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f)); // 1.0f爲透明度 ,值從0-1.0,依次變得不透明
// 畫圖
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(1));
g2d.draw
//釋放對象
//透明度設置 結束
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.dispose();
// 保存文件
ImageIO.write(image, "png", new File("c:/test.png"));這樣繪製的圖形應該說是前景透明的,背景依然是黑色,:(
網上沒有看到有益的代碼,在csdn上一位說自己實現了,但卻沒有說怎麼實現的,沒辦法只能自己摸索了,耗了半個多小時,幾乎查看了BufferedImage 和Graphics2D 所有方法和屬性,終於找到了解決方案,只不過是增加兩行代碼而已,如下:
int width = 400;
int height = 300;
// 創建BufferedImage對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取Graphics2D
Graphics2D g2d = image.createGraphics();
// ---------- 增加下面的代碼使得背景透明 -----------------
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
// ---------- 背景透明代碼結束 -----------------
// 畫圖
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(1));
g2d.draw
//釋放對象
g2d.dispose();
// 保存文件
ImageIO.write(image, "png", new File("c:/test.png"));