图片Base64

package org.xi.quick.test.imgbase64;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String base64 = getImageBase64("/Users/xi/Pictures/59794eedbbad7.jpg");
        String base64_2 = getImageBase64_2("/Users/xi/Pictures/59794eedbbad7.jpg");
        String type = "jpg";
        GenerateImage(base64, "/Workspace/github.com/java/study/test/target/111." + type);
        GenerateImage(base64_2, "/Workspace/github.com/java/study/test/target/333." + type);
    }

    final static Pattern headPattern = Pattern.compile("^data:image/[^;]*;base64,");
    final static Pattern typePattern = Pattern.compile("(?<=/)[^;]*");

    /**
     * 从图片文件获取Base64
     *
     * @param path
     * @return
     */
    static String getImageBase64(String path) {

        File file = new File(path);
        try (FileInputStream inputStream = new FileInputStream(file);
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            int rc;
            byte[] buff = new byte[1000];
            while ((rc = inputStream.read(buff, 0, 1000)) > 0) {
                outputStream.write(buff, 0, rc);
            }
            byte[] data = outputStream.toByteArray();
            return Base64.getEncoder().encodeToString(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从图片文件获取Base64
     *
     * @param path
     * @return
     */
    static String getImageBase64_2(String path) {

        File file = new File(path);
        try (FileInputStream inputStream = new FileInputStream(file);
             FileChannel fileChannel = inputStream.getChannel()) {

            ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
            fileChannel.read(byteBuffer);
            return Base64.getEncoder().encodeToString(byteBuffer.array());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取文件类型,从js转的base64适用
     *
     * @param base64
     * @return
     */
    static String getImageType(String base64) {

        String type = "png";
        Matcher matcher = headPattern.matcher(base64);
        if (matcher.find()) {
            String head = matcher.group();
            if ((matcher = typePattern.matcher(head)).find()) {
                type = matcher.group().toLowerCase();
                if (type.equals("jpeg")) type = "jpg";
            }
        }
        return type;
    }

    /**
     * 从base64生成图片
     *
     * @param base64
     * @param filePath
     */
    static void GenerateImage(String base64, String filePath) {

        if (base64 == null || base64.isEmpty()) return;

        try {
            base64 = headPattern.matcher(base64).replaceFirst("");
            //Base64解码
            byte[] data = Base64.getDecoder().decode(base64);
            for (int i = 0; i < data.length; ++i) {
                if (data[i] < 0) data[i] += 256;
            }
            //生成jpeg图片
            try (OutputStream out = new FileOutputStream(filePath)) {
                out.write(data);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从base64获取字节数组
     *
     * @param base64
     * @return
     */
    static byte[] getDataFromBase64(String base64) {

        //图像数据为空
        if (base64 == null || base64.isEmpty()) return null;

        // 如果是js传递去掉头,保留数据
        base64 = headPattern.matcher(base64).replaceFirst("");
        try {
            byte[] data = Base64.getDecoder().decode(base64);
            for (int i = 0; i < data.length; ++i) {
                if (data[i] < 0) data[i] += 256;
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

你可能感兴趣的:(图片Base64)