package org.fh.util;
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 ImageAnd64Binary {
public static void main(String[] args) {
String imgSrcPath = "H:/1.jpg";
String imgCreatePath = "H:/123.png";
imgCreatePath = imgCreatePath.replaceAll("\\\\", "/");
System.out.println(imgCreatePath);
String strImg = getImageStr(imgSrcPath);
System.out.println(strImg);
generateImage(strImg, imgCreatePath);
}
public static String getImageStr(String imgSrcPath) {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgSrcPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeBase64String(data);
}
public static boolean generateImage(String imgStr, String imgCreatePath) {
if (imgStr == null)
return false;
try {
byte[] b = Base64.decodeBase64(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgCreatePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結