Base64字节码与图片之间的相互转换(Base64Util)

package com.hzmoko.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;


public class Base64Util {
     /**
       * 图片转为Base64字节码
       * @param path 图片路径
       * @return 返回base64字节码
       */
    public static String imageToBase64(String path) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Base64 base64 = new Base64();
        return base64.encodeToString(data);
    }

    /**
     * Base64字节码转图片
     * @param base64Str 字节码存储路径
     * @param path 文件存储路径
     * @return 返回true或者false
     */
    public static boolean base64ToImage(String base64Str, String path) {
        if (base64Str == null){
            return false;
        }
        Base64 base64 = new Base64();
        try {
            byte[] bytes = base64.decodeBase64(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            File img = new File(path);
            if (!img.getParentFile().exists()) {
                img.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

你可能感兴趣的:(java工具类)