图片与Base64之间的互相转换

一定要引入import java.util.Base64包,不然会有问题

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @Author: 
 * @Date: 2019/4/18 17:00
 * @Description: 图片与base64之间的互相转换
 */
public class ImageToBase64 {
    private static Logger logger = LoggerFactory.getLogger(ImageToBase64.class);
    /**
     * @Description: 将base64编码字符串转换为图片
     * @param imgStr base64编码字符串
     * @param path   图片路径-具体到文件
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null) {
            return false;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            //解密
            byte[] b = decoder.decode(imgStr);
            //处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            if (!SSHValidateHelper.isEmpty(out)) {
                out.close();
            }
            return true;
        } catch (IOException e) {
            logger.error("将base64编码字符串转换为图片", e);
            return false;
        }
    }

    /**
     * 在线图片转换成base64字符串
     * @param imgURL 图片线上路径
     */
    public static String imageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            if (!SSHValidateHelper.isEmpty(is)) {
                is.close();
            }
            // 对字节数组Base64编码
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(data.toByteArray());
        } catch (IOException e) {
            logger.error("在线图片转换成base64字符串出现异常", e);
            return "";
        } finally {
            if (!SSHValidateHelper.isEmpty(data)) {
                try {
                    data.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据图片地址转换为base64编码字符串
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
            // 加密
            // BASE64Encoder encoder = new BASE64Encoder();
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(data);
        } catch (Exception e) {
            logger.error("根据图片地址转换为base64编码字符串出现异常", e);
            return "";
        } finally {
            if (!SSHValidateHelper.isEmpty(inputStream)) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String strImg = getImageStr("C:/Users/test.jpg");
        String strImg1 = imageToBase64ByOnline("http:7127220190111.jpg");
        System.out.println(strImg1);
        // System.out.println(strImg1);
        System.out.println(strImg.equals(strImg1));
        // generateImage(strImg, "F:/86619-107.jpg");
    }
}

你可能感兴趣的:(Java)