• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java 压缩图片大小

武飞扬头像
子不寐
帮助1

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
public class PictureUtil {
    private final static Logger logger = LoggerFactory.getLogger(PictureUtil.class);

    /**
     * 此种方法将原来的大文件替换成了小文件
     * @param originalFilePath          原图片所在的文件夹路径(D://xx/xx/xx.png)
     * @param originalFileObject        原图片路径 (D://xx/xx/xx.png)
     * @param originalFileExtensionName 原图片扩展名
     * @param originalFileName          原图片名
     * @param percent             压缩百分比
     */
    public static void Tosmallerpic(String originalFilePath, File originalFileObject, String originalFileExtensionName, String originalFileName, float percent) {
        Image src;
        try {
            src = javax.imageio.ImageIO.read(originalFileObject); //构造Image对象
            String img_midname = originalFilePath  "/"  originalFileName.substring(0, originalFileName.indexOf("."))   originalFileExtensionName;
            BufferedImage tag = new BufferedImage(src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_RGB);
            //tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
            tag.getGraphics().drawImage(src.getScaledInstance(src.getWidth(null), src.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            FileOutputStream newImage = new FileOutputStream(img_midname); //输出到文件流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            /* 压缩质量 */
            jep.setQuality(percent, true);
            encoder.encode(tag, jep);
            //encoder.encode(tag); //近JPEG编码
            newImage.close();
        } catch (IOException ex) {
            logger.error("图片压缩失败", ex);
        }
    }
}
学新通

此方法是上传图片工具类

import com.cnassets.commons.tools.constant.Constant;
import com.cnassets.commons.tools.utils.Result;
import com.cnassets.dto.UploadDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @Author z
 * @Date 2021/11/27 12:35
 * @Version 1.0
 */
@Component
public class ImagUtils {
    private final ResourceLoader resourceLoader;
    @Value("${web.profile}")
    private String path;

    public ImagUtils(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 单图片上传
     * @param file
     * @return
     */
    public Result<UploadDto> imgUpload(MultipartFile file) {

        if (file.isEmpty()) {
            return new Result<UploadDto>().error("文件不能为空");
        }
        try {
            //1.定义上传的文件
            String localPath = path;
            //2.获得文件名字
            String fileName = file.getOriginalFilename();
            //3.上传

            //3.1 生成新的文件路径和文件名
            String newfilename = FileNameUtils.getFileName(fileName);
//            String realPath =  FileNameUtils.datePath()   File.separator   FileNameUtils.getFileName(fileName);
            String realPath =  FileNameUtils.datePath()   File.separator   newfilename;
            // 保存的文件及文件地址
            String savePath = localPath   File.separator   realPath;
            //3.2 保存文件
            File dest = new File(savePath);
            //判断文件目目录是否存在,不存在则新建
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            // 新增 压缩文件
            PictureUtil.Tosmallerpic(localPath   File.separator FileNameUtils.datePath(), new File(savePath), newfilename.substring(newfilename.lastIndexOf(".")), newfilename, (float) 0.1);

            //保存路径到数据库
            String url = Constant.RESOURCE_PREFIX   File.separator   realPath;
            UploadDto uploadDto = new UploadDto();
            uploadDto.setFileName(fileName);
            uploadDto.setUrl(url);
            return new Result<UploadDto>().ok(uploadDto);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result<UploadDto>().error("文件上传失败");
        }
    }
}
学新通

上面的的类 在缩略图中有解释。这里只是添加了一个文件压缩的方法。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhahgji
系列文章
更多 icon
同类精品
更多 icon
继续加载