Я использую следующий код в приложении Spring Boot для загрузки изображения из папки ресурсов, кодировать его по строке Base64, а затем расшифрует его обратно в файл изображения. < /p>
public String encodeImageAsBase64(String imagePath) {
try {
logger.debug("Loading image from path: {}", imagePath);
Resource resource = resourceLoader.getResource("classpath:" + imagePath);
if (!resource.exists()) {
logger.error("Image not found at: {}", imagePath);
return "";
}
try (InputStream inputStream = resource.getInputStream()) {
byte[] imageBytes = inputStream.readAllBytes();
if (imageBytes.length == 0) {
logger.error("Empty image data for: {}", imagePath);
return "";
}
String base64String = Base64.getEncoder().encodeToString(imageBytes);
logger.info("base64String value {}", base64String);
logger.info("Base64 encoding success, length: {}", base64String.length());
return base64String;
}
} catch (Exception e) {
logger.error("Failed to encode image: {}", imagePath, e);
return "";
}
}
< /code>
При декодировании изображения с помощью кода выходное изображение кажется поврежденным. Однако, когда я использую одну и ту же строку Base64 в онлайн -инструменте, она работает нормально. Что может быть ошибка, которую я совершаю? Я использую java.util.base64; Springboot 3.* и Java17 < /p>
public void decodeBase64ToImage(String base64, String outputFilePath) {
try {
byte[] imageBytes = Base64.getDecoder().decode(base64);
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
fos.write(imageBytes);
fos.flush();
}
logger.info("Decoded image to: {}", outputFilePath);
} catch (Exception e) {
logger.error("Failed to decode image using : {}", outputFilePath, e);
}
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... cter-and-t