cn.jiangzeyin.Base64Util Maven / Gradle / Ivy
package cn.jiangzeyin;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
/**
* Created by jiangzeyin on 2018/3/27.
*/
public final class Base64Util {
private static final BASE64Encoder base64Encoder = new BASE64Encoder();
private static final BASE64Decoder base64Decode = new BASE64Decoder();
/**
* 编码流
*
* @param input 输出流
* @return 字符串
* @throws IOException io
*/
public static String encodeStream(InputStream input) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
// boolean var3 = false;
int rc;
while ((rc = input.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
return base64Encoder.encode(swapStream.toByteArray());
}
public static byte[] decodeByte(String base64Code) throws IOException {
return base64Decode.decodeBuffer(base64Code);
}
/**
* base64 的图片字符串生成文件
*
* @param imgStr 字符串
* @param path 文件位置
* @return true 生成功
* @throws IOException io
*/
public static boolean generateImage(String imgStr, String path) throws IOException {
if (StringUtil.isEmpty(imgStr)) {
return false;
}
byte[] b = base64Decode.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] = (byte) (b[i] + 256);
}
}
File f = new File(path);
File parent = f.getParentFile();
if (!parent.exists())
if (!parent.mkdirs())
throw new RuntimeException("create file error:" + parent.getParent());
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
}
public static String getEncode(byte[] src) {
return base64Encoder.encode(src);
}
}