图片处理工具「JAVA」

package com.michael.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 图片处理
 * <p>
 * Created by michael on 2015-12-21
 */
@Slf4j
public class ImageUtils {

    /**
     * 宽
     */
    private static final Integer WIDTH = 300;

    /**
     * 高
     */
    private static final Integer HEIGHT = 300;

    /**
     * 图片质量
     */
    private static final Float QUALITY = 0.9f;

    /**
     * 压缩图片
     *
     * @param sourceFilePath 源文件路径
     * @param newFilepath    新文件路径(即:压缩之后的文件路径)
     * @param width          宽
     * @param height         高
     * @param quality        图片质量
     * @return
     */
    public static String compression(String sourceFilePath, String newFilepath, int width, int height, float quality) {
        try {
            if (Strings.isEmpty(sourceFilePath))
                return null;

            File file = new File(sourceFilePath);
            if (!file.exists()) {
                log.warn("源文件不存在,请检查");
                throw new Exception("源文件不存在,请检查");
            }

            if (Strings.isNotEmpty(newFilepath)) {
                File f = new File(newFilepath);
                if (!f.exists())
                    f.mkdirs();
            }

            // 对服务器上的临时文件进行处理
            Image srcFile = ImageIO.read(new File(sourceFilePath));

            // 设定高宽
            BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bImage.getGraphics().drawImage(srcFile, 0, 0, width, height, null);

            // 压缩后的文件名
            String newFileAbsolutePath = newFilepath + "//" + Strings.uuid() + "_" + width + "×" + height + sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
            log.info("压缩图片路径:{}", newFileAbsolutePath);

            // 压缩之后存放位置
            FileOutputStream out = new FileOutputStream(newFileAbsolutePath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(bImage);

            // 压缩质量
            jep.setQuality(quality, true);
            encoder.encode(bImage, jep);
            out.close();

            return newFileAbsolutePath;

        } catch (FileNotFoundException e) {
            log.error("图片压缩过程中出错:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("图片压缩过程中出错:{}", e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("图片压缩过程中出错:{}", e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 压缩图片
     *
     * @param sourceFilePath 源文件路径
     * @param newFilepath    新文件路径(即:压缩之后的文件路径)
     * @return
     */
    public static String compression(String sourceFilePath, String newFilepath) {
        return compression(sourceFilePath, newFilepath, WIDTH, HEIGHT, QUALITY);
    }

    /**
     * 图片转换为byte数组
     *
     * @param path  图片绝对路径
     * @return
     */
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }

    /**
     * byte数组转换为图片
     *
     * @param data byte数组
     * @param path 输出路径, 如:F://Wallpaper//temp//XXXXXXXXX.jpg
     */
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            log.info("Make Picture success, Please find image in {}", path);

        } catch (Exception ex) {
            log.error("Exception: {}", ex);
            ex.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值