百度云-图像处理-动漫人物

图片转动漫人物接口

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.util.Base64Utils;
import org.apache.http.*;

import java.io.*;
import java.net.*;

public class selfie_anime {
	public static void main(String[] args) 
	{
		
		// 官网获取的 API Key 更新为你注册的
        String clientId = "API Key";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = " Secret Key";
        
		String access_token=getAuth(clientId, clientSecret);
		//调用人像动漫化
		String request_url="https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
		String url=request_url+"?access_token="+access_token;
	
		try {
			// 本地文件路径
            String fileDir = "本地文件路径";
            String fileName = "文件名.jpg";
            String filePath = fileDir + fileName;
            //文件读取
            FileInputStream fileInputStream = new FileInputStream(filePath);
            byte[] imgData = new byte[fileInputStream.available()];
            fileInputStream.read(imgData);
            String imgStr = new String(Base64Utils.encode(imgData));
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            //String params = "image=" + imgParam+"&type=anime_mask"+"&mask_id=5"; --带口罩
            String params = "image=" + imgParam+"&type=anime"; //不带口罩
            long startTime = System.currentTimeMillis(); //程序开始记录时间 
            //百度云上传文件
			String result = HttpUtil.post(url, access_token, "application/x-www-form-urlencoded", params);
			long endTime = System.currentTimeMillis(); //程序结束记录时间 
			long TotalTime = endTime - startTime; //总消耗时间
			System.out.println("time cost:"+TotalTime+"ms");
			System.out.println(result);
            fileInputStream.close();

            HashMap<String, Object> resMap = JSON.parseObject(result, new TypeReference<HashMap<String, Object>>() {
            });

            System.err.println(resMap.get("log_id"));
            //Base64转图片
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] decode = decoder.decode(String.valueOf(resMap.get("image")));
            for(int i=0; i< decode.length; i++){
                if(decode[i] < 0){
                    decode[i]+=256;
                }
            }
            Calendar calendar = Calendar.getInstance();
            String outFileName = calendar.getTimeInMillis()+".png";
            FileOutputStream out = new FileOutputStream(fileDir + outFileName);
            out.write(decode);
            out.flush();
            out.close();
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	//获取access_token
	public static String getAuth(String ak, String sk) 
	{
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            in.close();
            connection.disconnect();
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }


    static class HttpUtil{
	    public static String post( String url,String token,String contentType,String params ){
            CloseableHttpClient aDefault = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            RequestConfig config = RequestConfig.custom().setConnectTimeout(60 * 1000)
                    .setConnectionRequestTimeout(60 * 1000)
                    .setSocketTimeout(60 * 1000)
                    .setStaleConnectionCheckEnabled(true)
                    .build();

            httpPost.setConfig(config);
            httpPost.setHeader("Accept","application/json");
            httpPost.setHeader("Content-Type",contentType);
            httpPost.setEntity(new StringEntity(params,"utf-8"));
            CloseableHttpResponse response = null;
            try {
                response = aDefault.execute(httpPost);
               if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                   HttpEntity responseEntity = response.getEntity();
                   String res = EntityUtils.toString(responseEntity, "utf-8");
                   return res;
               }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(response != null){
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    aDefault.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return "";
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码途乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值