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

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


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值