阿里雲內容管理圖片校驗簡單使用

最近在搞論壇 論壇可以發圖片和文字,所以要保證圖片文字的安全性
對於文字校驗 之前發過一篇DFA文字校驗的 https://blog.csdn.net/java_ying/article/details/102902525
這篇主要記錄阿里與圖片校驗的使用
其實使用步驟阿里雲官網已經介紹的很完全了(認真臉,可能是實習生寫的文檔吧,唉)
sdk寫的也很棒(哪個人寫的,出來我絕對不打死你)
1、首先你要有個阿里雲帳號
2、然後要創建子賬號 拿到
accessKeyId=xxxx
accessKeySecret=xxx
這麼兩個寶貴的東西
3、開通內容管理的服務,不要怕,開通不要錢。好像是30天內免費使用
4、給你的帳號添加個AliyunYundunGreenWebFullAccess權限
在右上角訪問控制裏面
5、可以開始開發了
重新排號
1、首先你要有個maven工程
2、然後你要有個配置文件,名爲config,properties
#阿里雲accessKeyId、accessKeySecret
accessKeyId=xxx
accessKeySecret=xx
#調用阿里綠網服務的regionId,支持cn-shanghai
regionId=cn-beijing

你要有上面三個配置
3、然後pom文件添加依賴

	<dependency>
		<groupId>com.aliyun</groupId>
		<artifactId>aliyun-java-sdk-core</artifactId>
		<version>3.5.0</version>
	</dependency>
	<dependency>
		<groupId>com.aliyun</groupId>
		<artifactId>aliyun-java-sdk-green</artifactId>
		<version>3.5.0</version>
	</dependency>

4、然後就簡單了 copy 官方sdk的sample就可以了 簡單改一改即可用

package com.hqjl.communityserv.imageCheck;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by liuhai.lh on 17/01/12.
 */
public class BaseRequest {

    private static final Logger logger = LoggerFactory.getLogger(BaseRequest.class);

    protected static String accessKeyId;
    protected static String accessKeySecret;

    protected static String regionId;

    static {
        Properties properties = new Properties();

        try {
            properties.load(BaseRequest.class.getResourceAsStream("/config.properties"));
            accessKeyId = properties.getProperty("accessKeyId");
            accessKeySecret = properties.getProperty("accessKeySecret");
            regionId = properties.getProperty("regionId");
        } catch(IOException e) {
            logger.error(e.getMessage(), e);
        }

    }


    protected static String getDomain(){
         if("cn-shanghai".equals(regionId)){
             return "green.cn-shanghai.aliyuncs.com";
         }

         if ("cn-beijing".equals(regionId)) {
            return "green.cn-beijing.aliyuncs.com";
         }

         if ("ap-southeast-1".equals(regionId)) {
            return "green.ap-southeast-1.aliyuncs.com";
         }

         if ("us-west-1".equals(regionId)) {
            return "green.us-west-1.aliyuncs.com";
         }

         return "green.cn-shanghai.aliyuncs.com";
    }

    protected static String getEndPointName(){
        return regionId;
    }

}

package com.hqjl.communityserv.imageCheck;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author chunying.wang
 */
@Component
public class ImageSyncScanRequest extends BaseRequest {

    private final Logger LOG = LoggerFactory.getLogger(ImageSyncScanRequest.class);
    private final String AD = "ad";
    private final String PASS = "pass";

    public Boolean checkPic(String url) throws Exception{
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(getEndPointName(), regionId, "Green", getDomain());
        IAcsClient client = new DefaultAcsClient(profile);

        com.aliyuncs.green.model.v20180509.ImageSyncScanRequest imageSyncScanRequest = new com.aliyuncs.green.model.v20180509.ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        imageSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定請求方法
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setRegionId(regionId);


        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", url);
        task.put("time", new Date());

        tasks.add(task);
        JSONObject data = new JSONObject();
        /**
         * porn: 色情
         * terrorism: 暴恐
         * qrcode: 二維碼
         * ad: 圖片廣告
         * ocr: 文字識別
         */
        data.put("scenes", Arrays.asList(AD));
        data.put("tasks", tasks);

        imageSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 請務必設置超時時間
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        try {
            HttpResponse httpResponse = client.doAction(imageSyncScanRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
//                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if(200 == ((JSONObject)taskResult).getInteger("code")){
                            JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject)sceneResult).getString("scene");
                                String suggestion = ((JSONObject)sceneResult).getString("suggestion");
                                //根據scene和suggetion做相關的處理
                                if (!suggestion.equals(PASS)){
                                    return false;
                                }
//                                System.out.println("args = [" + scene + "]");
//                                System.out.println("args = [" + suggestion + "]");
                            }
                        }else{
                            LOG.error("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
                            LOG.error("msg=" + scrResponse.getString("msg"));
                            return false;
                        }
                    }
                } else {
                    LOG.error("detect not success. code:" + scrResponse.getInteger("code"));
                    LOG.error("msg=" + scrResponse.getString("msg"));
                    return false;
                }
            } else {
                LOG.error("response not success. status:" + httpResponse.getStatus());
                LOG.error(httpResponse.toString());
                return false;
            }
        } catch (ServerException e) {
            LOG.error(e.getMessage(), e);
            return false;
        } catch (ClientException e) {
            LOG.error(e.getMessage(), e);
            return false;
        } catch (Exception e){
            LOG.error(e.getMessage(), e);
            return false;
        }

        return true;
    }
}

簡單的把url變成參數,把日誌輸出改成Logger 就ok了,
這裏會有很多坑,傳給他們的url需要是全路徑,訪問時間根據圖片下載時間定,所以我用的是阿里雲存圖片。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章