获取图片失败: Invalid argument to native writeImage
Java    public static byte[] getUrlImageBytes(String url, int width, int height) {
        try {
            // 直接从网络读取图片并调整大小
            BufferedImage image = Thumbnails.of(new URL(url)).size(width, height).asBufferedImage();
            try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
                ImageIO.write(image, "jpg", baos);
                return baos.toByteArray();
            }
        } catch (IOException e) {
            log.error("获取图片失败: " + e.getMessage());
        }
        return null;
    }
图片实际大小小于Thumbnails设置的大小,导致缩放失败,从而获取图片失败
javapublic static byte[] getUrlImageBytes(String url, int width, int height) {
    try {
        // 从网络读取图片
        BufferedImage image = ImageIO.read(new URL(url));
        if (image == null) {
            log.error("获取图片失败: 图片为空");
            return null;
        }
        // 获取原始图片的宽高
        int originalWidth = image.getWidth();
        int originalHeight = image.getHeight();
        // 如果原始图片的尺寸小于目标尺寸,则不进行缩放
        if (originalWidth < width || originalHeight < height) {
            width = originalWidth;
            height = originalHeight;
        }
        // 调整图片大小
        BufferedImage resizedImage = Thumbnails.of(image).size(width, height).asBufferedImage();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(resizedImage, "jpg", baos);
            return baos.toByteArray();
        }
    } catch (IOException e) {
        log.error("获取图片失败: " + e.getMessage());
    }
    return null;
}
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!