您的位置:首页 > 编程语言 > Java开发

java的图片背景透明及透明度处理

2013-07-05 15:22 751 查看
如题,以下为通过java实现的针对图片的背景透明及透明度处理,供大家需要时参考:

/**
* 设置源图片为背景透明,并设置透明度
* @param srcFile 源图片
* @param desFile 目标文件
* @param alpha 透明度
* @param formatName 文件格式
* @throws IOException
*/
public static void transparentImage(String srcFile,String desFile,int alpha,String formatName) throws IOException{
BufferedImage temp =  ImageIO.read(new File(srcFile));//取得图片
transparentImage(temp, desFile, alpha, formatName);
}
/**
* 设置源图片为背景透明,并设置透明度
* @param srcImage 源图片
* @param desFile 目标文件
* @param alpha 透明度
* @param formatName 文件格式
* @throws IOException
*/
public static void transparentImage(BufferedImage srcImage,
String desFile, int alpha, String formatName) throws IOException {
int imgHeight = srcImage.getHeight();//取得图片的长和宽
int imgWidth = srcImage.getWidth();
int c = srcImage.getRGB(3, 3);
//防止越位
if (alpha < 0) {
alpha = 0;
} else if (alpha > 10) {
alpha = 10;
}
BufferedImage bi = new BufferedImage(imgWidth, imgHeight,
BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明
{
for(int j = 0; j < imgHeight; ++j)
{
//把背景设为透明
if(srcImage.getRGB(i, j) == c){
bi.setRGB(i, j, c & 0x00ffffff);
}
//设置透明度
else{
int rgb = bi.getRGB(i, j);
rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
bi.setRGB(i, j, rgb);
}
}
}
ImageIO.write(bi, StringUtils.isEmpty(formatName)?FORMAT_PNG:formatName, new File(desFile));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息