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

本文提供了一种使用Java实现图片背景透明及调整透明度的方法。该方法通过读取原始图片,将其转换为支持透明度的格式,并允许用户指定输出文件名、透明度级别和文件格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题,以下为通过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));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值