一.背景
工作中接触到需要采集并管理大量图片的需求,本来是用的FastDFS,但是发现实际情况是在项目实施时难以找到linux服务器去安装FastDFS,所以经过调研,选择了可以在windows服务器上安装部署的Go-FastDFS文件服务器
二.Go-FastDFS简介
go-fastdfs是一个基于http协议的分布式文件系统,它基于大道至简的设计理念,一切从简设计,使得它的运维及扩展变得更加简单,它具有高性能、高可靠、无中心、免维护等优点。
三.安装Go-FastDFS文件服务器
1)下载地址:https://github.com/sjqzhang/go-fastdfs/releases
2)下载完成直接启动fileserver.exe
3)验证是否安装成功,访问localhost:8080
4)验证上传功能,点击选择文件选择好文件后,点击上传
5)在返回的url后加?download=0,查看图片
四.实例实现功能
1)图片上传
2)图片删除
3)图片访问
4)图片水印添加
五.创建Spring boot项目,写代码实现功能
1)pom.xml添加依赖
<!--工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
2)核心代码,使用go-fastdhs上传图片并添加水印及删除图片工具类
@Component
public class GoFastdfsClientUtil {
@Value("${camera.upload.path}")
private String uploadPath;
@Value("${camera.delete.path}")
private String deletePath;
private final Logger logger = LoggerFactory.getLogger(GoFastdfsClientUtil.class);
/**
* 图片上传
*
* @param file
* @param sixCode
* @return
* @throws IOException
*/
public UploadResult upload(MultipartFile file, String sixCode) throws IOException {
UploadResult uploadResult = new UploadResult();
ByteArrayOutputStream bos = addWatermark(file, sixCode);
byte[] b = bos.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
InputStreamResource isr = new InputStreamResource(byteArrayInputStream, file.getOriginalFilename());
Map<String, Object> params = new HashMap<>();
params.put("file", isr);
params.put("path", "image");
params.put("output", "json");
// 场景
params.put("scene", "image");
String resp = HttpUtil.post(uploadPath, params);
Console.log("resp: {}", resp);
JSONObject exJson = JSONObject.parseObject(resp);
uploadResult = JSON.toJavaObject(exJson, UploadResult.class);
return uploadResult;
}
/**
* 图片删除
*
* @param fileUrl
*/
public void deleteImage(String md5) {
if (StringUtils.isEmpty(md5)) {
return;
}
try {
Map<String, Object> params = new HashMap<>();
params.put("md5", md5);
HttpUtil.post(deletePath, params);
} catch (Exception e) {
logger.warn(e.getMessage());
}
}
/**
* 加水印
*
* @param myfile
* @param sixCode
* @return
* @throws IOException
*/
private ByteArrayOutputStream addWatermark(MultipartFile myfile, String sixCode) throws IOException {
InputStream in = myfile.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
BufferedImage image = ImageIO.read(bis);
int height = image.getHeight();
int width = image.getWidth();
// 加水印
Graphics2D g = image.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setColor(new Color(128, 128, 128));
// 字体
int num = 0;
if (width > height) {
num = height / 30;
} else {
num = width / 30;
}
g.setFont(new Font("微软雅黑", Font.PLAIN, num));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = formatter.format(new Date());
String watermarkContent = "拍摄时间:" + date + "&摄像头编码:" + sixCode;
// 设置水印坐标
String[] split = watermarkContent.split("&");
int x = 10;
int y = height - 10;
for (int i = 0; i < split.length; i++) {
g.drawString(split[i], x, y -= g.getFontMetrics().getHeight());
}
g.dispose();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", bos);
return bos;
}
}
解释:这里我们事先在配置文件中配置好了文件的上传路径以及删除路径,配置如下:
camera:
upload:
path: http://localhost:8080/group1/upload
delete:
path: http://localhost:8080/group1/delete
visit:
path: http://localhost:8080
3)上面的方法中我们将图片上传后的返回值转换为结果集对象,对象定义如下:
public class UploadResult implements Serializable{
/**
*
*/
private static final long serialVersionUID = 5534287808864118463L;
private String url;
private String md5;
private String path;
private String domain;
private String scene;
private BigInteger size;
private BigInteger mtime;
private String scenes;
private String retmsg;
private int retcode;
private String src;
......get,set方法.....
}
4)在实际应用中编写控制层方法调用核心工具类的上传,删除方法即可
总结:本次总结主要描述了spring boot集成go-fastdfs上传图片的核心方法,没有具体的测试展示,其实go-fastdfs的使用很简单,接口编写也很简单
有疑问加站长微信联系(非本文作者)