优米格
分享有营养的

Java实现图片压缩

BraUndress.png

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.yomige.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];
    }
}

赞(0)
未经允许禁止转载:优米格 » Java实现图片压缩

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系