50,526
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
String filePath = "D:/source.png"; // 图片资源路径
String writePath = "D:/target/target.png"; //要写入的图片路径及名称
writeImage(getImageStr(filePath), writePath);
}
// 图片转Base64
private static String getImageStr(String imgPath) {
byte[] data = null;
InputStream input = null;
try {
input = new FileInputStream(imgPath);
data = new byte[input.available()];
input.read(data);
return new String(Base64.encodeBase64String(data));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return StringUtils.EMPTY;
}
// Base64转图片
private static void writeImage(String imgStr, String writePath) {
try {
byte[] bytes = Base64.decodeBase64(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0)
bytes[i] += 256;
}
OutputStream out = new FileOutputStream(writePath);
out.write(bytes);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}