Base64字符串转换为图片和图片PNG格式转JPG格式

Base64字符串转换为图片和图片PNG格式转JPG格式

package com.weige.entranceguard.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * base64与图片互转
 */
public class Base64Utils {

    private static String JPG = "jpg";
    private static String PNG = "png";

    /**
     * base64转文件并输出到指定目录
     *
     * @param base64Str
     * @param fileName
     * @param filePath
     * @return
     */
    public static byte[] decode(String base64Str, String fileName, String filePath) {
        File file = null;
        //创建文件目录
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;

        byte[] b = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            b = decoder.decodeBuffer(replaceEnter(base64Str));
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return b;
    }

    /**
     * 根据图片byte数组转Base64字符串
     * @param image
     * @return
     */
    public static String encode(byte[] image) {
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    /**
     * 根据图片uri转Base64字符串
     * @param uri
     * @return
     */
    public static String encode(String uri) {
        BASE64Encoder encoder = new BASE64Encoder();
        return replaceEnter(encoder.encode(uri.getBytes()));
    }

    /**
     * @return
     * @path 图片路径
     */
    public static byte[] imageTobyte(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 (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public static String replaceEnter(String str) {
        String reg = "[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    /**
     * 判断图片base64字符串的文件格式
     * @param base64ImgData
     * @return
     */
    public static String checkImageBase64Format(String base64ImgData) {
        byte[] b = Base64.getDecoder().decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "jpg";
        }
        return type;
    }

    /**
     * PNG格式图片转换为JPG
     * @param pngFilePath
     * @param jpgFilePath
     * @return
     */
    public static boolean png2jpeg(String pngFilePath,String jpgFilePath){
        File file = new File(pngFilePath);
        file.canRead();
        BufferedImage bi = null;
        boolean flag = false;
        try {
            //png格式转换为jpg格式
            bi = ImageIO.read(file);
            BufferedImage newBufferedImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(bi,0,0, Color.WHITE,null);
            flag = ImageIO.write(newBufferedImage,"jpg",new File(jpgFilePath));
            return flag;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * base64转png图片再转jpg图片再转化为base64
     * @param baseStr
     * @param filePath
     * @return
     */
    public static String conver(String baseStr,String filePath){
        String type = Base64Utils.checkImageBase64Format(baseStr);
        if (JPG.equals(type)){
            return baseStr;
        }else if (PNG.equals(type)){
            Long time = System.currentTimeMillis();
            String pngName = time.toString()+".png";
            decode(baseStr, pngName, filePath);
            String pngPath = filePath + pngName;
            String jpgName = time.toString()+".jpg";
            String jpgPath = filePath + jpgName;
            boolean isSuccess = png2jpeg(pngPath,jpgPath);
            if (isSuccess){
                byte[] jpgBytes =imageTobyte(jpgPath);
                String str = encode(jpgBytes);
                return str;
            }
        }
        return baseStr;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值