智能云端素材库后端-图片功能扩展

以图搜图

接入百度以图搜图API,功能实现类似爬虫。

颜色搜索

限定在个人空间内搜索。

将在上传图片时将主色调作为图片的属性进行保存。

搜索时计算颜色的相似度,根据相似度返回结果。

相似度计算方法有很多,这里使用欧几里得距离计算。

图片批量管理

可以使用线程池+分批+并发实现。

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
49
50
51
52
@Resource
private ThreadPoolExecutor customExecutor;

/**
* 批量编辑图片分类和标签
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void batchEditPictureMetadata(PictureBatchEditRequest request, Long spaceId, Long loginUserId) {
// 参数校验
validateBatchEditRequest(request, spaceId, loginUserId);

// 查询空间下的图片
List<Picture> pictureList = this.lambdaQuery()
.eq(Picture::getSpaceId, spaceId)
.in(Picture::getId, request.getPictureIds())
.list();

if (pictureList.isEmpty()) {
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "指定的图片不存在或不属于该空间");
}

// 分批处理避免长事务
int batchSize = 100;
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < pictureList.size(); i += batchSize) {
List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));

// 异步处理每批数据
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
batch.forEach(picture -> {
// 编辑分类和标签
if (request.getCategory() != null) {
picture.setCategory(request.getCategory());
}
if (request.getTags() != null) {
picture.setTags(String.join(",", request.getTags()));
}
});
boolean result = this.updateBatchById(batch);
if (!result) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量更新图片失败");
}
}, customExecutor);

futures.add(future);
}

// 等待所有任务完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
}

AI图片编辑

使用阿里云百炼API接入AI图片编辑模型。

异步任务优化

可以使用消息队列(RabbitMQ,Kafka)对异步任务进行管理。

图库分析

将图库的资源、图片分类、图片标签、图片大小等数据进行统计并返回给前端。