Java 图片压缩

4 篇文章 0 订阅
1 篇文章 0 订阅

压缩思路

通过 BufferedImage.getGraphics().drawImage(Image.getScaledInstance()) 压缩图片。

Image.getScaledInstance(width, height, hints) 的hints为压缩模式,本文采用 Image.SCALE_SMOOTH 生成缩略图片的平滑度的,优先级比速度高,生成的图片质量比较好但速度慢

源码


import com.hyxf.open.common.util.FileUtil;
import com.hyxf.open.common.util.StreamUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


public class ImageTest {

    public static void main(String[] args) {
        test();
    }

    public static void test() {
        String sPath = "D:\\tmp\\image\\pngFile.png";
        String dPath = "D:\\tmp\\image\\tmp33.jpg";

        try {
            InputStream contentStream = new FileInputStream(sPath);

            InputStream result = reduce(contentStream, dPath);
            System.out.println(StreamUtils.stream2Base64String(result));
            result.close();
            FileUtil.delete(dPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载并压缩图片
     *
     * @param contentStream
     * @param localPath
     * @return
     */
    public static InputStream reduce(InputStream contentStream, String localPath) {
        try {
            File file = new File(localPath);
            inputstreamTofile(contentStream, file);

            System.out.println("start reduce");
            reduceImg(localPath, localPath);

            System.out.println("finished");

            InputStream n = new FileInputStream(localPath);
            return n;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件
     * @param ins
     * @param file
     * @throws IOException
     */
    public static void inputstreamTofile(InputStream ins, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }

    public static void reduceImg(String imgsrc, String imgdist) {
        try {
            File srcfile = new File(imgsrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            int[] results = getImgWidthHeight(srcfile);

            int widthdist = results[0];
            int heightdist = results[1];
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage( widthdist,  heightdist, BufferedImage.TYPE_INT_RGB);

            // 这边是压缩的模式设置
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            FileOutputStream out = new FileOutputStream(imgdist);
            //将图片按JPEG压缩,保存到out中
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            //关闭文件输出流
            out.close();
        } catch (Exception ef) {
            ef.printStackTrace();
        }
    }

    /**
     * 获取图片宽度和高度
     *
     * @param file 图片路径
     * @return 返回图片的宽度
     */
    public static int[] getImgWidthHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = { 0, 0 };
        try {
            // 获得文件输入流
            is = new FileInputStream(file);
            // 从流里将图片写入缓冲图片区
            src = ImageIO.read(is);
            // 得到源图片宽
            result[0] =src.getWidth(null);
            // 得到源图片高
            result[1] =src.getHeight(null);
            is.close();  //关闭输入流
        } catch (Exception ef) {
            ef.printStackTrace();
        }
        return result;
    }

}

问题及解决方案

在服务器编译时报 com.sun.image.codec.jpeg 包找不到。

原因:java1.8开始,包名用的是oracle,而不是sun,因此需要特殊引用。在本地编译时,idea会把jdk1.8自动引入,但服务器maven编译时不会,需添加maven配置如下。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <!-- 解决maven命令编译报错,因为rt.jar 和jce.jar在jre的lib下面,不在jdk的lib下面,导致maven找不到(java7以后会出现这个问题),将这2个jar包拷贝到jdk的lib下面估计也好使-->
        <compilerArguments>
            <verbose/>
            <bootclasspath>${java.home}/lib/rt.jar${path.separator}${java.home}/lib/jce.jar</bootclasspath>
        </compilerArguments>
        <encoding>utf-8</encoding>
    </configuration>
</plugin>

 

参考文献

https://www.cnblogs.com/xsl1995/p/10318499.html

https://blog.csdn.net/pmdream/article/details/84305019

https://blog.csdn.net/x_lord/article/details/74311764

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值