Java - 图片压缩(返回压缩后图片的base64字符串)

前言:

  • 压缩时间较长, 5M左右的图片压缩至500k左右大概需要2秒左右;
  • Demo中返回base64字符串, 可根据自己需求改返回值类型;

环境:

  • JDK 1.8
  • IDEA 2021.3

注意:

  • 本人只测试了两种类型的图片(jpg/png),其他类型还需自行测试;
  • png类型的图片有点特殊,只能用另个开源组件进行压缩;

具体请看代码:

<!-- 处理除png以外的图片 -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

<!-- 处理png类型的图片 -->
<dependency>
    <groupId>org.jpedal</groupId>
    <artifactId>OpenViewerFX</artifactId>
    <version>6.6.14</version>
</dependency>

import com.idrsolutions.image.png.PngCompressor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Base64;
import java.util.Optional;

/**
 * 图片工具类
 */
@Slf4j
public class ImageUtil {

    /**
     *  压缩图片,返回base64字符串
     *  接收MultipartFile格式文件;
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public static String compressImageByMultipartFile(MultipartFile multipartFile) throws Exception {
        File sourceFile = MultipartFileToFile(multipartFile);
        return compressImageByFile(sourceFile);
    }

    /**
     * 将MultipartFile转换为File
     */
    public static File MultipartFileToFile(MultipartFile multiFile) throws IOException {
        String fileName = multiFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        InputStream in = null;
        OutputStream out = null;
        try {
            File file = File.createTempFile(fileName, prefix);
            out = new FileOutputStream(file);
            in = multiFile.getInputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, read);
            }
            return file;
        } catch (Exception e) {
            throw e;
        }finally {
            if (in != null){
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }

    /**
     * 压缩jpg图片,返回base64字符串
     * sourceFile: 源文件;
     */
    public static String compressImageByFile(File sourceFile) throws Exception {
        log.info("原文件大小:[{}]",sourceFile.length());
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            //大于500K进行压缩:
            if (sourceFile.length() > 500 * 1024) {
                String fileName = sourceFile.getName();
                String prefix = fileName.substring(fileName.lastIndexOf(".")+1);
                if ("png".equals(prefix.toLowerCase())){
                    PngCompressor.compress(sourceFile,sourceFile);
                }else {
                    //sourceFile = getCompressFile(sourceFile,0.15f);
                    Thumbnails.of(sourceFile).scale(1f).outputQuality(0.1f).toFile(sourceFile);
                }
                log.info("文件格式:[{}] -- 压缩后文件大小:[{}]",prefix,sourceFile.length());
            }

            in = new FileInputStream(sourceFile);
            out = new ByteArrayOutputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, read);
            }
            return Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }

    /**
     * 如果接口超时时间允许,也可以递归处理压缩,以至于达到最理想的压缩大小;
     * @param file
     * @param quality
     * @return
     * @throws IOException
     */
    private static File getCompressFile(File file,float quality) throws IOException {
        Thumbnails.of(file).scale(1f).outputQuality(quality).toFile(file);
        if(quality <= 0.1f || file.length() <= 500 * 1024){
            return file;
        }else{
            quality = quality - 0.05f;
            return getCompressFile(file,quality);
        }
    }
}

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

@RestController
public class ImageDemoController {

    /** main方法测试 */
    public static void main(String[] args) {
        try {
            File file = new File("C:/原图片.jpg");
            String s = ImageUtil.compressImageByFile(file);
            System.out.println("压缩后图片的base64字符串::" + s);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /** 项目中测试 */
    @PostMapping("/test/compressImage")
    public  String compressImage(MultipartFile file){
        try {
            String s = ImageUtil.compressImageByMultipartFile(file);
            System.out.println("压缩后图片的base64字符串::" + s);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "成功";
    }

}

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
原文:https://github.com/yangchenjava/com.yangc.utils cache EhCacheUtils - 基于ehcache的工具类 LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于memcached的工具类 RedisUtils - 基于redis的工具类,与redis的集群配置无缝结合 db JdbcUtils - 操作jdbc的工具类 MongodbUtils - 操作mongodb的工具类 email EmailUtils - 邮件工具类,支持发送带附件的邮件 encryption AesUtils - 实现AES加密解密 Base64Utils - 实现Base64加密解密 Md5Utils - 获取字符串或文件的md5 excel ReadExcel2003 - 以model方式读2003版Excel(大数据) ReadExcel2007 - 以sax方式读2007版Excel(大数据) WriteExcel - 写Excel image CaptchaUtils - 生成验证码 ImageUtils - 图片压缩、截图 QRCodeUtils - 生成二维码、解析二维码 io SerializeUtils - 序列化、反序列化对象 ZipUtils - 压缩、解压文件 json JsonUtils - json格式转换 lang CharsetDetectorUtils - 获取文本文件编码格式 ChineseCalendar - 农历日历 ConvertUtils - 高低字节转换 DateUtils - 日期工具类 HtmlFilterUtils - 过滤html标签 JsoupUtils - 基于jsoup过滤html标签 MoneyUtils - 获取大写金额 NumberUtils - 数字工具类 PinyinUtils - 汉字转拼音 media MediaUtils - 基于ffmpeg,qtfaststart,yamdi的多媒体工具类 net AttachmentUtils - HTTP文件下载防止中文乱码 FastDFSUtils - 操作FastDFS的工具类 FtpUtils - 操作FTP的工具类(基于sun自家的包,jdk7以后不建议使用) FtpUtilsApache - 基于apache操作FTP的工具类 HttpUtils - 发送HTTP请求 IpUtils - 获取IP SFtpUtils - 操作SFTP的工具类 prop PropertiesUtils - 操作properties配置文件
你可以使用Java的`java.util.zip`和`java.util.Base64`类来压缩和编码Base64图片。 下面是一个示例代码,展示了如何压缩Base64图片: ```java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; public class ImageCompression { public static String compressImageToBase64(String base64Image) throws IOException { // 将Base64字符串解码为字节数组 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 创建一个新的字节数组输出流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 创建一个压缩输出流,并将其连接到字节数组输出流 DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(outputStream, new Deflater()); // 将图像字节数组写入压缩输出流 deflaterOutputStream.write(imageBytes); deflaterOutputStream.close(); // 获取压缩后的图像字节数组 byte[] compressedImageBytes = outputStream.toByteArray(); // 将压缩后的图像字节数组编码为Base64字符串 String compressedBase64Image = Base64.getEncoder().encodeToString(compressedImageBytes); return compressedBase64Image; } } ``` 使用示例: ```java String base64Image = "your_base64_image_here"; try { String compressedBase64Image = ImageCompression.compressImageToBase64(base64Image); System.out.println("Compressed Base64 Image: " + compressedBase64Image); } catch (IOException e) { e.printStackTrace(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值