最近遇到一个挺离谱的功能,某个表单只让上传一张图,多图上传会使导出失败。跟开发沟通后表示,这个问题处理不了。我...
遂自己思考,能否以曲线救国的方式拯救一下,即不伤及代码之根本,又能解决燃眉之急。灵光一闪,想到了美图救救的图片拼接功能。于是就想着尝试一下是否可行。
考虑到图片拼接界限等,目标实现:白色图片背景(默认是黑色),以最大图片的宽为最终拼接图片的宽,图片纵向拼接,图与图之间间隔35px。代码如下(异常捕获、空值判断、权限判断等需自行完善):
java">import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;@RestController
public class ImagePinJie {@PostMapping("/imgPinJie")public String imageUpload(@RequestParam("files") MultipartFile[] files) throws IOException {if (files.length == 0) {return "没有文件被上传";}List<BufferedImage> bufferedImages = new ArrayList<>();List<Integer> widths = new ArrayList<>();List<Integer> heights = new ArrayList<>();for (MultipartFile file : files) {if (!file.isEmpty()) {try {BufferedImage bi = ImageIO.read(file.getInputStream());bufferedImages.add(bi);widths.add(bi.getWidth());heights.add(bi.getHeight());} catch (Exception e) {return "上传失败: " + e.getMessage();}}}BufferedImage bufferedImage = imgPinJie(bufferedImages, widths, heights);createImage(bufferedImage);return "上传成功";}public BufferedImage imgPinJie(List<BufferedImage> bufferedImages, List<Integer> widths, List<Integer> heights) {int maxWidth = widths.stream().mapToInt(Integer::intValue).max().getAsInt();int totalHeight = heights.stream().mapToInt(Integer::intValue).sum() + (heights.size() - 1) * 35;BufferedImage bufferedImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);int offset = 0;Graphics2D graphics = bufferedImage.createGraphics();graphics.setColor(Color.WHITE);graphics.fillRect(0, 0, maxWidth, totalHeight);for(BufferedImage bi : bufferedImages) {graphics.drawImage(bi, 0, offset, bi.getWidth(), bi.getHeight(), null);offset += bi.getHeight() + 35;}graphics.dispose();return bufferedImage;}public void createImage(BufferedImage bufferedImage) throws IOException {File file = new File("C:/Users/iTcys/Pictures/pinjie.png");ImageIO.write(bufferedImage, "png", file);}
}
接口测试
最终效果
至此,图片拼接完成了,接下来准备研究一下前端拼接的方式。