这是我的代码:
private Rectangle getImageUriImageSize(String uri) {
Matcher matcher = dataUriPattern.matcher(uri);
if (!matcher.find()) return null;
byte[] bytes = DatatypeConverter.parseBase64Binary(matcher.group(2));
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
Rectangle rectangle = null;
try {
BufferedImage bufferedImage = ImageIO.read(inputStream);
if (bufferedImage != null) {
rectangle = new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
}
} catch (IOException e) {
logger.warn("Error occurred when reading base64 Data URI: '{}'", e.getMessage());
} finally {
IOUtils.closeQuietly(inputStream);
}
return rectangle;
}
它给出了错误
exception: I/O error reading PNG header!
我改变了这个建议
https://stackoverflow.com/a/27108892
private Rectangle getImageUriImageSize(String uri) {
Matcher matcher = dataUriPattern.matcher(uri);
if (!matcher.find()) return null;
byte[] bytes = DatatypeConverter.parseBase64Binary(matcher.group(2));
InputStream in = new ByteArrayInputStream(bytes);
// ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
Rectangle rectangle = null;
try {
BufferedImage bufferedImage = ImageIO.read(in);
if (bufferedImage != null) {
rectangle = new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
}
} catch (IOException e) {
logger.warn("Error occurred when reading base64 Data URI: '{}'", e.getMessage());
} finally {
IOUtils.closeQuietly(in);
}
return rectangle;
}
但这次我遇到了错误。我使用docker,这个容器退出。
那该怎么办?
也是这个
public Rectangle getImageSize(String currentMerchant, String relativeUrl) {logger.info("getImageSize");
String imageUrl = getImageUrl(currentMerchant, relativeUrl);
Rectangle rect = null;
FileImageInputStream imageInputStream = null;
try {
File downloadedImageFile = restTemplate.execute(
imageUrl,
HttpMethod.GET,
null,
response -> {
InputStream inputStream = response.getBody();
String fileName = getFileName(relativeUrl);
return saveInputStreamAs(inputStream, fileName);
}
);
Iterator<ImageReader> imageReaders = getImageReaders(downloadedImageFile);
if (!imageReaders.hasNext()) {
logger.warn("Cannot find any image reader for file {}", downloadedImageFile);
}
ImageReader imageReader = imageReaders.next();
imageInputStream = new FileImageInputStream(downloadedImageFile);
imageReader.setInput(imageInputStream, true, true);
rect = new Rectangle(0, 0, imageReader.getWidth(0), imageReader.getHeight(0));
} catch (HttpStatusCodeException ex) {
logger.warn("Error getting image resource from url '{}', status: {}, message: {}", imageUrl, ex.getStatusCode(), ex.getResponseBodyAsString());
} catch (IOException ex) {
logger.warn("Could not read image by url '{}', exception: {}", imageUrl, ex.getMessage(), ex);
} finally {
IOUtils.closeQuietly(imageInputStream);
}
return rect;
}
错误就在这里
catch (IOException ex) {
logger.warn("Could not read image by url '{}', exception: {}", imageUrl, ex.getMessage(), ex);
}
答案 0 :(得分:1)
请检查您传递的文件扩展名。它应该是PNG。