当前位置:   article > 正文

springboot整合百度AI的图片和文字违规识别_springboot 上传图片是否违规

springboot 上传图片是否违规

调用百度AI的图片和文字违规识别

一、需要从百度AI开放平台下载依赖,导入依赖后,创建百度AI的properties文件

文件名:BaiDuAi.properties

baidu.API_KEY = ****
baidu.SECRET_KEY = *****
  • 1
  • 2

二、加载配置文件类

文件名:BaiduAiConfig

import lombok.Data;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource("classpath:BaiDuAi.properties")
public class BaiduAiConfig{
    private String appkey;
    private String secretkey;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

三、创建httputil类并设置ContentType为application/x-www-form-urlencoded

HttpClientUtils

    public static JSONObject  doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                //设置ContentType为application/x-www-form-urlencoded
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

            {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                JSONObject jsonObject = JSONObject.parseObject(strResult);
                return jsonObject;
            }
            else
            {
                logger.error("get请求提交失败:" + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

四、封装一个util类,分别加入以下代码

获取accesstoken 调用百度AI都必须要这个accesstoken ,每获取一次在百度ai会存储20天左右, 为了避免不必要的请求,建议存到redis中,先从redis中获取,等过期后再通过调用接口获取

//    获取accesstoken
    public String getaccesstoken(String appkey,String secretkey){
        try {
            JSONObject jsonObject = HttpClientUtils.httpGet("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+appkey+"&client_secret="+secretkey);
            String accesstoken = jsonObject.getString("access_token");
            return accesstoken;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

请求文本审核接口

//    文本审核
    public JSONObject textcensorString(String accesstoken,String text){
        try {
            Map<String, String> param = new HashMap<>();
            param.put("text",text);
            JSONObject jsonObject = HttpClientUtils.doPost("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token="+accesstoken, param);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

处理文本审核返回的json(这个可根据自己的需求来)

    public JSONObject textcensorname(JSONObject obj, JedisClient jedisClient,BaiduAiConfig baiduAiConfig) throws Throwable {
        String getaccesstoken = jedisClient.get("BAIDUAO_TOCKEN");
        if(getaccesstoken==null){
            getaccesstoken=getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        JSONObject jsonObject = textcensorString(getaccesstoken,obj.toJSONString());
        if(jsonObject.getInteger("error_code")!=null&&110==(jsonObject.getInteger("error_code"))||jsonObject.getInteger("error_code")!=null&&111==(jsonObject.getInteger("error_code"))){
            getaccesstoken = getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jsonObject = textcensorString(getaccesstoken,obj.toJSONString());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        return jsonObject;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

请求图片审核接口

//    图片审核
    public JSONObject imgcensorString(String accesstoken,String base64EncoderImg){
        try {
            Map<String, String> param = new HashMap<>();
            param.put("image",base64EncoderImg);
            JSONObject jsonObject = HttpClientUtils.doPost("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token="+accesstoken, param);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

图片转base64

    public String multipartFileToBASE64(MultipartFile mFile) throws Exception{
        BASE64Encoder bEncoder=new BASE64Encoder();
        String[] suffixArra=mFile.getOriginalFilename().split("\\.");
     /*   String preffix="data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);*/
        String base64EncoderImg=bEncoder.encode(mFile.getBytes()).replaceAll("[\\s*\t\n\r]", "");

        return base64EncoderImg;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

处理图片审核返回的json (这个可根据自己的需求来)

    public Boolean imgcensorname(String base64EncoderImg, JedisClient jedisClient,BaiduAiConfig baiduAiConfig) throws Throwable {
        String getaccesstoken = jedisClient.get("BAIDUAO_TOCKEN");
        if(getaccesstoken==null){
            getaccesstoken=getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        JSONObject jsonObject = imgcensorString(getaccesstoken,base64EncoderImg);
        if(jsonObject.getInteger("error_code")!=null&&110==(jsonObject.getInteger("error_code"))||jsonObject.getInteger("error_code")!=null&&111==(jsonObject.getInteger("error_code"))){
            getaccesstoken = getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jsonObject = textcensorString(getaccesstoken,base64EncoderImg);
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        System.out.println(jsonObject);
        if(2==(jsonObject.getInteger("conclusionType"))){

            return false;
        }
        return true;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/355592?site
推荐阅读
相关标签
  

闽ICP备14008679号