/*
* base64位图片加密
*/
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/*
* base64位图片解密
*/
public static boolean generateImage(String imgStr,String imgpath) { // 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
String imgFilePath = imgpath;// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
//测试下
public class Image {
public static void main(String[] args) {
String image = getImageStr("C:/Users/jt/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/forum/upload/555555555.jpeg") ;
System.out.println(image);
String s = "" ;
generateImage(s, "路径");
}
Base64位图片上传和解密
最新推荐文章于 2024-07-15 00:00:26 发布