在服务器端将 base64 字符串转换为图像 java
Convert base64 string to image at server side in java
我有 base64 字符串,我想将其转换回图像,而不管服务器端的图像格式如何。我通过使用以下代码进行了尝试,正在创建图像,但是当我尝试预览它时,显示错误无法加载图像。
public void convertStringToImage(String base64) {
try {
byte[] imageByteArray = decodeImage(base64);
FileOutputStream imageOutFile = new FileOutputStream("./src/main/resources/demo.jpg");
imageOutFile.write(imageByteArray);
imageOutFile.close();
} catch (Exception e) {
logger.log(Level.SEVERE, "ImageStoreManager::convertStringToImage()" + e);
}
}
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
我应该怎么做才能让我的图片看起来正常?
试试这个:
public static byte[] decodeImage(String imageDataString) {
return org.apache.commons.codec.binary.Base64.decodeBase64(imageDataString.getBytes());
}
您的代码看起来不错。不过,我可以为您建议一些更多的调试步骤。
- 手动编码您的文件,例如使用 webpage
- 比较
String base64
是否包含与您在页面上看到的内容完全相同的内容。 // 如果这里有问题,您的请求已损坏,可能是前端的一些编码问题?
- 查看在
./src/main/resources/demo.jpg
下创建的文件内容并比较内容(大小,二进制比较)//如果这里有问题你会知道实际上保存操作被破坏了
备注:
- 您是否尝试在关闭前执行
.flush()
?
- 您当前形式的代码可能会导致资源泄漏,请查看try-with-resources
我有 base64 字符串,我想将其转换回图像,而不管服务器端的图像格式如何。我通过使用以下代码进行了尝试,正在创建图像,但是当我尝试预览它时,显示错误无法加载图像。
public void convertStringToImage(String base64) {
try {
byte[] imageByteArray = decodeImage(base64);
FileOutputStream imageOutFile = new FileOutputStream("./src/main/resources/demo.jpg");
imageOutFile.write(imageByteArray);
imageOutFile.close();
} catch (Exception e) {
logger.log(Level.SEVERE, "ImageStoreManager::convertStringToImage()" + e);
}
}
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
我应该怎么做才能让我的图片看起来正常?
试试这个:
public static byte[] decodeImage(String imageDataString) {
return org.apache.commons.codec.binary.Base64.decodeBase64(imageDataString.getBytes());
}
您的代码看起来不错。不过,我可以为您建议一些更多的调试步骤。
- 手动编码您的文件,例如使用 webpage
- 比较
String base64
是否包含与您在页面上看到的内容完全相同的内容。 // 如果这里有问题,您的请求已损坏,可能是前端的一些编码问题? - 查看在
./src/main/resources/demo.jpg
下创建的文件内容并比较内容(大小,二进制比较)//如果这里有问题你会知道实际上保存操作被破坏了
备注:
- 您是否尝试在关闭前执行
.flush()
? - 您当前形式的代码可能会导致资源泄漏,请查看try-with-resources