图片Base64加密、解密与图片压缩---随笔

导入Maven依赖

 <dependency>
   <groupId>commons-codec</groupId>
     <artifactId>commons-codec</artifactId>
     <version>1.12</version>
 </dependency>
 <dependency>
     <groupId>net.coobird</groupId>
     <artifactId>thumbnailator</artifactId>
     <version>0.4.9</version>
 </dependency>

编码实现

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

import static java.util.regex.Pattern.compile;

/**
 * @author savesl
 */
public class ImageUtil {
    public static Logger logger =  Logger.getLogger(ImageUtil.class);

    /**
     * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     * @param imgPath 生成64编码的图片的路径
     * @return
     */
    public static String imageToBase64String(String imgPath){
        InputStream in = null;
        byte[] data = null;
        String imgStr = "";
        BASE64Encoder base64Encoder = new BASE64Encoder();
        //读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            //对字节数组Base64编码
            imgStr = base64Encoder.encode(data);
        } catch (IOException e) {
            logger.error("后台异常",e);
        } finally {
            data = null;
            base64Encoder = null;
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }

        }
        //返回Base64编码过的字节数组字符串
        return imgStr;
    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     * @param imgBase64      ase64图片字符串
     * @param imgPath     存储图片的目标路径
     * @return
     */
    public static boolean base64StringToImage(String imgBase64, String imgPath) {
        byte[] imgBytes = null;
        OutputStream out = null;
        if (StringUtil.isNotBlank(imgBase64)) {
            try {
                // Base64转换成byte数组,转化为输入流
                imgBytes = new BASE64Decoder().decodeBuffer(
                        compile("data:image/\\w{1,5};base64,").matcher(imgBase64).replaceFirst(""));
                // 如果 简析成功,将图片上传至指定文件目录
                for (int i = 0; i < imgBytes.length; ++i) {
                    if (imgBytes[i] < 0) {
                        imgBytes[i] += 256;
                    }
                }
                // 新生成的图片
                out = new FileOutputStream(imgPath);
                out.write(imgBytes);
                out.flush();
            } catch (Exception e) {
                logger.error("文件上传失败! 原因:" + e);
                System.err.println("文件上传失败! 原因:" + e);
                return false;
            } finally {
                imgBytes = null;
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                    }
                }
            }
        } else {
            logger.error("base64图片为空!");
            return false;
        }
        return true;
    }

    /**
     * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     * @param imgSrcPath 生成64编码的图片的路径
     * @return
     */
    public static String getImageBase64Str(String imgSrcPath){
        InputStream in = null;
        byte[] data = null;
        byte[] encodeBase64 = null;
        String imgStr = "";
        //读取图片字节数组
        try {
            in = new FileInputStream(imgSrcPath);
            data = new byte[in.available()];
            in.read(data);
            encodeBase64 = Base64.encodeBase64(data);
            imgStr = new String(encodeBase64);
        } catch (IOException e) {
            logger.error("后台异常",e);
        } finally {
            data = null;
            encodeBase64 = null;
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }

        //返回Base64编码过的字节数组字符串
        return imgStr;
    }

    /**
     * 使用指定的base64图片字符串 生成图片文件到指定目录下
     * @param imgStr   图片base64字符串
     * @param imgCreatePath  图片存储目录
     * @return
     */
    public static boolean generateBase64Image(String imgStr, String imgCreatePath){
        //图像数据为空
        if (imgStr == null){
            return false;
        }
        byte[] b = null;
        OutputStream out = null;
        try {
            //Base64解码
            b = Base64.decodeBase64(imgStr);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {
                    b[i]+=256;
                }
            }
            out = new FileOutputStream(imgCreatePath);
            out.write(b);
            out.flush();
            return true;
        } catch (Exception e){
            return false;
        } finally {
            b = null;
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 返回图片的长和宽
     * @param imagePath 图片路径
     * @return
     * @throws IOException
     */
    public static Map<String,String> getImageInfo(String imagePath){
        Map<String,String> infoMap = new HashMap<>();
        InputStream is = null;
        BufferedImage src = null;
        try{
            is=new FileInputStream(imagePath);
            //构造Image对象
            src = javax.imageio.ImageIO.read(is);
            //得到源图宽
            int srcWidth = src.getWidth(null);
            //得到源图长
            int srcHeight = src.getHeight(null);
            infoMap.put("width", srcWidth+"");
            infoMap.put("height", srcHeight+"");
        }
        catch(IOException ioe){
            logger.error("获取图片尺寸时发生了异常!", ioe);
            throw new RuntimeException(ioe);
        } finally {
            if(null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            src = null;

        }
        return infoMap;
    }

    /**
     * 校验图片分辨率
     * @param imagePath    图片的物理路径
     * @param imageHeight  图片的高
     * @param imageWidth   图片的宽
     */
    public static boolean checkImageResolution(String imagePath,String imageHeight,String imageWidth){
        Map<String,String> imageInfo=getImageInfo(imagePath);
        String currentImageHeight=imageInfo.get("width");
        String currentImageWidth=imageInfo.get("height");
        logger.debug("tag:currentImageWidth:"+currentImageWidth+","+"currentImageHeight:"+currentImageHeight);
        if(imageHeight.equals(currentImageHeight)&&imageWidth.equals(currentImageWidth)){
            return true;
        }
        return false;
    }

    /**
     * 校验图片分辨率是否在给定的尺寸范围内
     * @param imagePath    图片的物理路径
     * @param imageHeight  图片的高
     * @param imageWidth   图片的宽
     */
    public static boolean checkImageSize(String imagePath,int imageHeight,int imageWidth){
        Map<String,String> imageInfo=getImageInfo(imagePath);
        String currentImageHeight=imageInfo.get("width");
        String currentImageWidth=imageInfo.get("height");
        if(imageHeight >= Integer.parseInt(currentImageHeight) && imageWidth >= Integer.parseInt(currentImageWidth)){
            return true;
        }
        return false;
    }

    /**
     * 改变图标尺寸大小,可以用作压缩图片
     * @return
     */
    public static boolean changeImgSize(String imagePath,int width,int height){
        boolean flag = false;
        try{
            File f = new File(imagePath);
            //压缩图片
            if(f.getName().endsWith(".png")){
                Thumbnails.of(f).size(width, height).outputFormat("png").toFile(f);
                changeImgSuffix(f,"png");
            }else{
                Thumbnails.of(f).size(width, height).toFile(f);
            }
            flag = true;
        } catch (IOException ioe) {
            logger.error("改变图片分辨率时候出错", ioe);
        }
        return flag;
    }

    /**
     * 修改文件的后缀名称
     * @param f 文件
     * @param suffix 后缀名称
     * @return
     */
    public static void changeImgSuffix(File f, String suffix){
        String filename = f.getPath();
        filename = filename.substring(0, filename.lastIndexOf(".") + 1)+suffix;
        f.renameTo(new File(filename));
    }

    /**
     * 正则表达式校验图片名称 是否符合要求
     * @return
     */
    public static boolean checkImgNameByRegex(File f,String regex){
        return f.getName().matches(regex);
    }

    /**
     * 压缩图片到指定大小以下
     * @param imagePath 图片文件路径
     * @param size 指定目标图片大小 (KB)
     * @return
     */
    public static boolean compressToTheSize(String imagePath, int size) {
        //压缩率 0.9
        final float rate = 0.9F;
        File file = new File(imagePath);
        if(file.exists()) {
            //判断图片是否已经压缩到小于指定的大小
            int count = 0;
            while(file.length() > 1024 * size) {
                System.out.println("目前图片大小:" + file.length()/1024 + "KB,第"+(++count)+"次压缩图片!");
                Map<String, String> imageInfo = getImageInfo(imagePath);
                int width = Integer.parseInt(imageInfo.get("width"));
                int height = Integer.parseInt(imageInfo.get("height"));
                //图片缩放0.8倍
                width *= rate;
                height *= rate;
                //压缩
                boolean changeImgSize = changeImgSize(imagePath, width, height);
                System.out.println("压缩结果:" + changeImgSize);
            }
            System.out.println("最终图片大小:" + file.length()/1024 + "KB");
            return true;
        }
        return false;
    }

    /**
     * 将指定路径的图片压错为指定大小并转化为Base64字符串
     * @param imgPath
     * @param sizekb
     * @return
     */
    public static String imageTransitionBase64BySize(String imgPath, int sizekb){
        File imgFile = new File(imgPath);
        if(imgFile.exists()) {
            //如果文件大于200KB,则压缩图片文件
            if(imgFile.length() > 1024*sizekb) {
                compressToTheSize(imgPath, 200);
            }
            //图片转base64字符串
            String imgBase64 = getImageBase64Str(imgPath);
            return imgBase64;
        }
        return null;
    }


}

你可能感兴趣的:(java)