vue+java实现图片批量压缩
最近做了一个功能批量图片压缩在不对接第三方api的条件下应该怎么做先看看效果https://office.zjdiante.com/imageTool/compress1.安装 ImageMagick我用的版本是72.后端代码工具类package com.ruoyi.basicTool.imageTool.utils; import cn.hutool.core.io.IoUtil; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; /** * 调用本机 ImageMagick 7 命令行默认可执行文件名为 {code magick}。 * p解析顺序系统属性 {code imagemagick.binary}可由 {code application.yml} 中 {code imagemagick.binary} 在启动时注入 * → 环境变量 {code IMAGEMAGICK_BINARY} → Windows 下默认 {code magick.exe} → 其他系统默认 {code magick}。/p * pWindows 若未将安装目录加入 PATH请将 {code imagemagick.binary} 设为 {code magick.exe} 的绝对路径例如 * {code C:/Program Files/ImageMagick-7.1.1-Q16-HDRI/magick.exe}。/p */ public final class ImageMagickRunUtils { private static final int MAGICK_TIMEOUT_SECONDS 120; private ImageMagickRunUtils() { } public static String magickBinary() { String p System.getProperty(imagemagick.binary); if (StringUtils.isNotEmpty(p)) { return p.trim(); } String env System.getenv(IMAGEMAGICK_BINARY); if (StringUtils.isNotEmpty(env)) { return env.trim(); } if (System.getProperty(os.name, ).toLowerCase(Locale.ROOT).contains(windows)) { return magick.exe; } return magick; } public static void runMagick(Path expectedOut, ListString cmd) throws Exception { ProcessBuilder pb new ProcessBuilder(cmd); pb.redirectErrorStream(true); Process proc; try { proc pb.start(); } catch (IOException e) { if (e.getMessage() ! null (e.getMessage().contains(error2) || e.getMessage().contains(Cannot run program))) { throw new IOException( 无法启动 ImageMagick进程找不到可执行文件。CMD 能运行 magick 不代表 JVM 的 PATH 相同 请在 CMD 执行 where magick 得到 magick.exe 绝对路径写入 application.yml 的 imagemagick.binary 或设置环境变量 IMAGEMAGICK_BINARY。, e); } throw e; } String output; try (InputStream es proc.getInputStream()) { if (!proc.waitFor(MAGICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { proc.destroyForcibly(); throw new IOException(ImageMagick 执行超时); } output IoUtil.readUtf8(es); } if (proc.exitValue() ! 0) { throw new IOException(ImageMagick 失败: truncate(output, 800)); } if (!Files.exists(expectedOut) || Files.size(expectedOut) 0) { throw new IOException(ImageMagick 未生成有效输出: truncate(output, 800)); } } private static String truncate(String s, int max) { if (s null) { return ; } String t s.replace(\r, ).replace(\n, ).trim(); return t.length() max ? t : t.substring(0, max) ...; } }有想要做类似不明白的小伙伴可以点开https://office.zjdiante.com/ 联系我