欢迎光临
感受代码之美

Java实现图片压缩

Java实现图片压缩的代码示例如下:

package org.4spaces;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * Created by 四个空格-https://www.4spaces.org on 2017/1/11.
 */
public class ImgCompressUtil {
    public static void main(String[] args) {
        BufferedImage bufferedImage = ImgCompressUtil.compressImageByPercent("F:\\child.jpg", 0.1);
        File destFile = ImgCompressUtil.saveAsImage("F:\\child_copy.jpg", bufferedImage);
        System.out.println(ImgCompressUtil.readableFileSize(destFile.length()));
    }

    /**
     * 按比例压缩图片
     *
     * @param originFilePath  原始文件("c:\\1.png")
     * @param compressPercent 压缩比例(压缩为原来一半传0.5)
     * @return
     */
    public static BufferedImage compressImageByPercent(String originFilePath, double compressPercent) {
        BufferedImage img = null;//原图
        BufferedImage bufferedImage = null;//压缩后图
        int width, height;
        try {
            File file = new File(originFilePath);
            img = ImageIO.read(file);
            width = (int) (img.getWidth() * compressPercent);
            height = (int) (img.getHeight() * compressPercent);
            bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bufferedImage.getGraphics().drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedImage;
    }


    /**
     * 保存压缩后的图片
     *
     * @param fullFilePath  保存路径
     * @param bufferedImage 压缩后的图片
     */
    public static File saveAsImage(String fullFilePath, BufferedImage bufferedImage) {
        File destFile = null;
        try {
            destFile = new File(fullFilePath);
            FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
            ImageIO.write(bufferedImage, "png", out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return destFile;
    }

    /**
     * 文件大小格式化
     *
     * @param size
     * @return
     */
    public static String readableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

转载请注明来源:四个空格 » Java实现图片压缩

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址