栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java 压缩图片大小】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java 压缩图片大小】

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);
​
    
    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;
​

@Component
public class ImagUtils {
    private final ResourceLoader resourceLoader;
    @Value("${web.profile}")
    private String path;
​
    public ImagUtils(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
​
    
    public Result imgUpload(MultipartFile file) {
​
        if (file.isEmpty()) {
            return new Result().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().ok(uploadDto);
​
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error("文件上传失败");
        }
    }
}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/760378.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号