调用 ImageReader getHeigth 后 PNG 文件损坏

问题描述 投票:0回答:1

打电话后我的 png 文件损坏了:

BufferedImage im = ImageIO.read(inputStream);

您将在下面找到服务生命周期:

InputStream inputStream = multipartFile.getInputStream();
throwExceptionIfImageDimensionsNotValid(inputStream);
storeIntoFileSystem(inputStream);

实施

private void throwExceptionIfImageDimensionsNotValid(InputStream inputStream) throws IOException, StoreFileException {
        
        BufferedImage im = ImageIO.read(inputStream);
        
        if(isImageWidthHeightRatioOk(im.getHeight(), im.getWidth())) {
            return;
        } else {
            throw new StoreFileException("Le rapport hauteur / largeur de limage doit etre compris entre 0.55 et 0.625");
        }
    }

存储文件实现:

void storeIntoFileSystem(InputStream inputStreamIn) throws IOException{
        try (InputStream inputStream = inputStreamIn) {
            Path targetDirectoryPath = Paths.get("Files-Upload/");
            Path filePath = Paths.get("Files-Upload/").resolve("pacman_preview.png");

            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException ioe) {
            throw new IOException("Could not save file: " , ioe);
        }
    }

执行后,pacman_preview.png 图像出现在文件上传文件夹中。

问题是: 当我在操作系统图像查看器中打开文件时,我收到以下消息:

无法加载图像...读取 PNG 图像文件时发生致命错误。不是 PNG 文件

注意:当 throwExceptionIfImageDimensionsNotValid(inputStream) 被注释时,图像打开正确。

java image inputstream javax.imageio java.nio.file
1个回答
0
投票

InputStream 是一个流——如果你读了它,它就完成了。你无法再读一遍。在这种情况下,您必须再次打开流,例如:

InputStream inputStream = multipartFile.getInputStream();
throwExceptionIfImageDimensionsNotValid(inputStream);
inputStream = multipartFile.getInputStream();
storeIntoFileSystem(inputStream);
© www.soinside.com 2019 - 2024. All rights reserved.