sharp-fileupload图片处理ImageService(三)

创建名字图片

方法

/**
 * 创建名字图片
 * @param text 张三
 * @param groupName 存储
 * @param storeName 存储的文件名,可能是用户的id
 * @return
 * @throws IOException
 */
public String createImage(String text, String groupName, String storeName) throws IOException

测试

String url = imageService.createImage("张三", "header");
String url = imageService.createImage("张三", "header", "Rick");

输出

http://localhost:7892/header/475290263729115136.png

http://localhost:7892/header/Rick.png

http://xhope.top/wp-content/uploads/2021/10/475098507762896896.png

图片处理

public FileMeta cropPic(FileMeta fileMeta, ImageParam imageParam) throws IOException;

测试

@Test
@Order(1)
public void testCropPic() throws IOException {
    File file = new File("/Users/rick/jkxyx205/tmp/fileupload/demo/1.jpg");
    FileMeta fileMeta = FileMetaUtils.parse(file);

    // 裁剪9:5
    ImageParam imageParam = new  ImageParam();
    imageParam.setRw(9);
    imageParam.setRh(5);

    FileMeta cropPicFileMeta = imageService.cropPic(fileMeta, imageParam);
    // 将裁剪的存储到磁盘
    List<? extends FileMeta> crop = fileStore.storeFileMeta(Arrays.asList(cropPicFileMeta), "crop");
    System.out.println(crop.get(0).getUrl());
}

图片浏览

依赖图片裁剪,通过Response的输出流实现图片浏览的功能

public void write(FileMeta fileMeta, ImageParam imageParam, OutputStream os) throws IOException

测试

/**
 * http://localhost:8080/images/475036437923139584?p=0&rw=9&rh=5&r=30&w=500
 * 原图按9:5裁剪,旋转30度,宽度500像素
 * 图片查看
 * @param request
 * @param response
 * @param imageParam
 */
@GetMapping("/{id}")
public void preview(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id, ImageParam imageParam) throws IOException {
    Document document = documentService.findById(id);
    imageService.write(document, imageParam, HttpServletResponseUtils.getOutputStreamAsView(request, response, document.getFullName()));
}