图片自动审核
查看API文档
https://help.aliyun.com/document_detail/70292.html
https://help.aliyun.com/document_detail/53424.html?spm=a2c4g.11186623.6.599.234f4cacLe1pyG
没什么好说的 基本和 官方sdk文档一致
package com.lyra.utils;
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.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.lyra.enums.ReviewStatus;
import com.lyra.utils.extend.AliyunResources;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
@Component
public class ReviewImageUtils {
@Autowired
private AliyunResources aliyunResources;
public boolean reviewImage(String imageURL) {
IClientProfile profile = DefaultProfile
.getProfile("cn-shanghai", aliyunResources.getAccessKeyId(), aliyunResources.getAccessKeySecret());
try {
DefaultProfile
.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
} catch (ClientException e) {
e.printStackTrace();
return false;
}
IAcsClient client = new DefaultAcsClient(profile);
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
// 指定API返回格式。
imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
// 指定请求方法。
imageSyncScanRequest.setMethod(MethodType.POST);
imageSyncScanRequest.setEncoding("utf-8");
// 支持HTTP和HTTPS。
imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
JSONObject httpBody = new JSONObject();
/**
* 设置要检测的风险场景。计费依据此处传递的场景计算。
* 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
* 例如,检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
* porn:表示鉴黄场景。
*/
httpBody.put("scenes", Arrays.asList("porn"));
/**
* 设置待检测图片。一张图片对应一个task。
* 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
* 通常情况下批量检测的平均响应时间比单张检测的要长。一次批量提交的图片数越多,响应时间被拉长的概率越高。
* 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task。
*/
JSONObject task = new JSONObject();
task.put("dataId", UUID.randomUUID().toString());
// 设置图片链接。
task.put("url", imageURL);
task.put("time", new Date());
httpBody.put("tasks", Arrays.asList(task));
imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
"UTF-8", FormatType.JSON);
/**
* 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
* 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常。
*/
imageSyncScanRequest.setConnectTimeout(3000);
imageSyncScanRequest.setReadTimeout(10000);
HttpResponse httpResponse = null;
try {
httpResponse = client.doAction(imageSyncScanRequest);
} catch (Exception e) {
e.printStackTrace();
}
// 服务端接收到请求,完成处理后返回的结果。
if (httpResponse != null && httpResponse.isSuccess()) {
JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
System.out.println(JSON.toJSONString(scrResponse, true));
int requestCode = scrResponse.getIntValue("code");
// 每一张图片的检测结果。
JSONArray taskResults = scrResponse.getJSONArray("data");
if (200 == requestCode) {
for (Object taskResult : taskResults) {
// 单张图片的处理结果。
int taskCode = ((JSONObject) taskResult).getIntValue("code");
// 图片对应检测场景的处理结果。如果是多个场景,则会有每个场景的结果。
JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
if (200 == taskCode) {
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject) sceneResult).getString("scene");
String suggestion = ((JSONObject) sceneResult).getString("suggestion");
// 根据scene和suggestion做相关处理。
// 根据不同的suggestion结果做业务上的不同处理。例如,将违规数据删除等。
System.out.println("scene = [" + scene + "]");
System.out.println("suggestion = [" + suggestion + "]");
return suggestion.equalsIgnoreCase(ReviewStatus.pass.getType());
}
} else {
// 单张图片处理失败, 原因视具体的情况详细分析。
System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
return false;
}
}
} else {
/**
* 表明请求整体处理失败,原因视具体的情况详细分析。
*/
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
return false;
}
}
return false;
}
}
检测图片 若图片为违规图片 将图片链接设置为默认图片皆可
上传图片时调用此方法检测即可
private String reviewImage(String imageURL) {
String realImage = DEFAULTS_IMAGE;
boolean result = false;
result = reviewImageUtils.reviewImage(imageURL);
if (result) {
realImage = imageURL;
}
return realImage;
}
public GraceJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile multipartFile) throws IOException {
if (multipartFile != null && StringUtils.isNotBlank(userId)) {
String fileUrl = uploadService.uploadFile(multipartFile, userId);
log.info("upload file path:{}", fileUrl);
// return GraceJSONResult.ok(reviewImage(fileUrl));
return GraceJSONResult.ok(fileUrl);
}
return GraceJSONResult.errorCustom(ResponseStatusEnum.UPLOAD_FAILED);
}
虽然道路是曲折的,但前途是光明的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律