Java图片工具类

该图片工具类功能:校验图片比例、图片压缩、图片转码为Base64、Base64字符串转化成图片、把图片路径转码、人脸切图(只适用于百度人脸检测接口返回的坐标点)、图片Base64解码并输出流、图片Base64编码转成输入流。
package com.blog.chen_2890.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

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

/**
 * @description 图片工具类
 * @date 2019/5/7 15:01
 * @author https://blog.csdn.net/chen_2890
 */
public class ImgUtils {

    /**
     * @description 校验图片比例
     * @param file  图片
     * @param imageWidth 宽
     * @param imageHeight 高
     * @return boolean true:符合要求
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:13
     * @version V1.0
     */
    public static boolean checkImageScale(File file, int imageWidth, int imageHeight) throws IOException {

        Boolean result = false;
        if (!file.exists()) {
            return false;
        }
        BufferedImage bufferedImage = ImageIO.read(file);
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (imageHeight != 0 && height != 0) {
            int scale1 = imageHeight / imageWidth;
            int scale2 = height / width;
            if (scale1 == scale2) {
                result = true;
            }
        }
        return result;
    }

    /**
     * @description 图片压缩
     * @param inputPath  原始图片路径
     * @param outputPath 输出图片路径
     * @param oldWidth   压缩前宽度
     * @param oldHeight  压缩前高度
     * @param newWidth   压缩后宽度
     * @param newHeight  压缩后高度
     * @return void
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:12
     * @version V1.0
     */
    public static void imgCompress(String inputPath, String outputPath, Double oldWidth, Double oldHeight, Double newWidth, Double newHeight) throws IOException {
        //将自定义宽高转换成对应比例
        double widthScale = newWidth / oldWidth;
        double heightScale = newHeight / oldHeight;

        //压缩
        Thumbnails.of(inputPath)
                .scale(widthScale, heightScale)
                .outputQuality(1d)
                .toFile(outputPath);
    }

    /**
     * @description 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     * @param path 图片路径
     * @return java.lang.String base64字符串
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:11
     * @version V1.0
     */
    public static String imgToBase64(String path) throws IOException {
        byte[] data = null;
        // 读取图片字节数组
        InputStream in = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回Base64编码过的字节数组字符串
        return Base64.encodeBase64String(data);
    }
    /**
     * @description 把图片路径转码
     * @param path 图片路径
     * @return java.lang.String
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:08
     * @version V1.0
     */
    public static String URLEncoder(String path) {
        try {
            path = URLEncoder.encode(path, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     *
     *
     * @description 人脸切图(只适用于百度人脸检测接口返回的坐标点)
     * @param imgBase64 图片Base64编码
     * @param x         人脸区域离左边界的距离
     * @param y         人脸区域离上边界的距离
     * @param width     人脸区域的宽度
     * @param height    人脸区域的高度
     * @return java.lang.String 切脸后Base64编码
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:07
     * @version V1.0
     */
    public static String cut(String imgBase64, double x, double y, double width, double height) throws IOException {
        //将浮点数转换成整型,由于百度人脸检测接口返回的y轴是眉毛位置的坐标点
        //因此需要把坐标点向头顶位置偏移,所以对坐标点进行修改,偏移量目前暂定为这些,后续可根据具体情况变更
        int xInt = new Double(Math.floor(x)).intValue() - 10;
        int yInt = new Double(Math.floor(y)).intValue() - 50;
        int widthInt = new Double(Math.ceil(width)).intValue() + 20;
        int heightInt = new Double(Math.ceil(height)).intValue() + 50;

        //切图
        InputStream inputStream = imgBase64ToInput(imgBase64);
        BufferedImage bufferedImage = Thumbnails.of(inputStream)
                .sourceRegion(xInt, yInt, widthInt, heightInt)
                .size(widthInt, heightInt)
                .outputQuality(1d)
                .asBufferedImage();
        //转base64
        BASE64Encoder encoder = new BASE64Encoder();

        //io流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        //写入流中
        ImageIO.write(bufferedImage, "jpg", baos);

        //转换成字节数组
        byte[] bytes = baos.toByteArray();

        //转换成base64串
        String newImgBase64 = encoder.encodeBuffer(bytes).trim();

        //删除 \r\n,注意:转换成base64串时,一定要删除\r和\n
        String newImg = newImgBase64.replaceAll("\n", "").replaceAll("\r", "");
        return newImg;
    }

    /**
     * @description 处理Base64解码并输出流
     * @param base64 图片Base64编码
     * @param out  OutputStream
     * @return boolean
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:06
     * @version V1.0
     */
    public static boolean base64ToImgOutput(String base64, OutputStream out) throws IOException {
        // 图像数据为空
        if (base64 == null) {
            return false;
        }
        try {
            // Base64解码
            byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            //生成jpeg图片
            out.write(bytes);
            out.flush();
            return true;
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @description 图片Base64编码转成输入流
     * @param imgBase64 图片Base64编码
     * @return java.io.InputStream
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:04
     * @version V1.0
     */
    public static InputStream imgBase64ToInput(String imgBase64) {
        ByteArrayInputStream stream = null;
        try {

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(imgBase64);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }

    /**
     * @description base64字符串转化成图片
     * @param imgBase64 base64字符串
     * @param imgPath 图片路径(绝对路径)
     * @return boolean
     * @author https://blog.csdn.net/chen_2890
     * @date 2019/5/18 20:02
     * @version V1.0
     */
    public static boolean imgBase64ToImage(String imgBase64,String imgPath){
        //图像数据为空
        if(imgBase64 == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgBase64);
            for(int i=0;i<b.length;++i){
                if(b[i]<0){
                    //调整异常数据
                    b[i]+=256;
                }
            }
            //生成图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }catch (Exception e){
             e.printStackTrace();
        }
        return false;
    }

}

要是还有不太明白的地方请留言,评论必回
要是对我的文章感兴趣的话,关注一下吧,谢谢!

上一篇:如何读取yml文件内容

下一篇:如何配置log4j

原来微信打赏还可以备注哦

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值