【人像分割】Java給透明圖片加背景色

目錄

調用百度AI人像分割接口

看一下示例圖轉換後的效果

給透明背景的圖片增加背景色

 先看個效果圖

Java代碼實現

調用示例代碼


之前在百度AI社區寫的人像分割帖子,最近有一些開發者會遇到返回的透明圖的base64存圖片有問題,還想知道存起來的透明圖片如何更改背景色,想快速做個證件照的應用。

此文呢。就從接口返回的透明圖片搞起。把返回的

foreground - 人像前景摳圖,透明背景

保存成png格式的圖片。並進行背景色修改。證件照尺寸修改就不演示了。畢竟還是要給大家一些自我發揮的機會的呢。

調用百度AI人像分割接口

註冊百度賬號、創建應用就不陳述了。

import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;

/**
* 調用百度AI 人像分割接口示例
* @author 小帥丶
* @Date 2019/10/11-15:56
**/
public class TestPersonSeg {
    public static void main(String[] args) {
        String APPID = "";
        String APIKEY = "";
        String SECRETKEY = "";
        AipBodyAnalysis client = new AipBodyAnalysis(APPID, APIKEY, SECRETKEY);
        String filePath = "F:\\testimg\\20151218164804_8kY2a.jpeg";
        //調用接口
        JSONObject object = client.bodySeg(filePath, null);
        String foreground = object.get("foreground").toString();
        //把foreground 保存成png格式的透明圖片
        GenerateImage(foreground, "F:\\testimg\\101103.png");
    }
    /**
* base64字符串轉化成圖片
* @param imgStr 接口返回的圖片base64數據
* @param imgFilePath 即將要保存的圖片的本地路徑包含文件名稱和格式 例如:F:/generateimage.jpg
* @return
*/
    public static boolean GenerateImage(String imgStr, String imgFilePath) { // 對字節數組字符串進行Base64解碼並生成圖片
        if (imgStr == null) // 圖像數據爲空
        return false;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            // Base64解碼
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) { // 調整異常數據
                    b[i] += 256;
                }
            }
            // 生成jpeg圖片
            OutputStream out = new FileOutputStream(imgFilePath); // 新生成的圖片
            out.write(b);
            out.flush();
            out.close();
            System.out.println("保存成功" + imgFilePath);
            return true;
        } catch(Exception e) {
            System.out.println("出錯了" + e.getMessage());
            return false;
        }
    }
}

 

看一下示例圖轉換後的效果

原圖
foreground - 人像前景摳圖,透明背景

 

 

scoremap - 人像前景灰度圖

給透明背景的圖片增加背景色

需要用到

BufferedImage.TYPE_INT_RGB 

源碼註釋解釋如下

Represents an image with 8-bit RGB color components packed intointeger pixels 就是8位RGB的圖像進行處理

 先看個效果圖

替換成粉色背景色

Java代碼實現

https://gitee.com/xshuai/imagetool/blob/master/src/main/java/cn/xsshome/imagetool/util/PngColoringUtil.java

這裏是代碼地址。imagetool項目裏面還有很多其他的圖片處理工具類哦 最好使用JDK1.8+

如果不是請替換bytes轉base64方法

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

/**
 * @Description 透明背景上色
 * @author 小帥丶
 * @className PngColoringUtil
 * @Date 2019/10/11-17:03
 **/
public class PngColoringUtil {
    /**
     * @Description 給PNG圖片增加背景色
     * @Author 小帥丶
     * @param sourceImage 原始圖片 最好是PNG透明的
     * @param targetImage 修改後的圖片
     * @param backgroudColor 背景色
     **/
    public static void changePNGBackgroudColor(String sourceImage, String targetImage, Color backgroudColor) {
        try {
            BufferedImage result = changePNGBackgroudColor(sourceImage, backgroudColor);
            File output = new File(targetImage);
            ImageIO.write(result, "jpg", output);
        } catch (IOException e) {
            System.out.println("有問題了" + e.getMessage());
        }
    }
    /**
     * @Description 給PNG圖片增加背景色 返回base64
     * @Author 小帥丶
     * @param sourceImage 原始圖片 最好是PNG透明的
     * @param backgroudColor 背景色
     * @return java.lang.String
     **/
    public static String changePNGBackgroudColorByBase64(String sourceImage, Color backgroudColor){
        try {
            String base64 = "";
            BufferedImage result = changePNGBackgroudColor(sourceImage, backgroudColor);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(result, "jpg", baos );
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
            final Base64.Encoder encoder = Base64.getEncoder();
            base64 = encoder.encodeToString(imageInByte);
            return base64;
        }catch (Exception e){
            System.out.println("有問題了" + e.getMessage());
            return null;
        }
    }
    /**
     * @Description 給PNG圖片增加背景色 返回BufferedImage
     * @Author 小帥丶
     * @param sourceImage 原始圖片 最好是PNG透明的
     * @param backgroudColor 背景色
     * @return BufferedImage
     **/
    public static BufferedImage changePNGBackgroudColor(String sourceImage, Color backgroudColor) {
        try {
            File input = new File(sourceImage);
            BufferedImage image = ImageIO.read(input);

            BufferedImage result = new BufferedImage(
                    image.getWidth(),
                    image.getHeight(),
                    BufferedImage.TYPE_INT_RGB);

            Graphics2D graphic = result.createGraphics();
            graphic.drawImage(image, 0, 0, backgroudColor, null);
            graphic.dispose();
            return result;
        } catch (IOException e) {
            System.out.println("有問題了" + e.getMessage());
            return null;
        }
      }
}

調用示例代碼

    public static void main(String[] args) throws Exception{
        String image = "F:\\testimg\\1011.png";//原始圖片路徑
        String resultImage = "F:\\testimg\\10111700.jpg";//更改背景色後的圖片路徑
        changePNGBackgroudColor(image,resultImage, Color.pink);//原圖 目標圖 背景色
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章