图片解码写入磁盘后打不开

Can't open image after decoding and writing to disk

我正在将 jpg 上传到 spring 控制器端点。图片以 Base64 image/jpg 的形式上传,以 MultipartFile 的形式出现。我正在使用 Base64Decoder 解码输入流,它似乎解码正常,但是当我将它转换为 InputStream 以将其写入磁盘时,我可以看到它已被修改(根据我在调试器中看到的内容)。当我保存文件并打开它时,它说它是不受支持的文件类型。

我将多部分输入流直接写入磁盘,我在记事本中看到了 base64 编码。

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBgRXhpZgAASUkqAAgAAAACADEBAgAHAAAAJgAAAGmHBAABAAAALgAAAAAAAABHb29nbGUAAAMAAJAHAAQAAAAwMjIwAqAEAAEAAAAACAAAA6AEAAEAAAAABgAAAAAAAP/bAIQAAwICCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCggKCgoKCgoICAgKCgoICAgICgoICAgKCgoICA0NCggNCAgKCAEDBAQGBQYIBgYICA0ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI/8AAEQgGAAgAAwEiAAIRAQMRAf/EAB0AAAIDAQEBAQEAAAAAAAAAAAMEAgUGAQAHCAn/xABJEAABAwIDBgQFBAIBAwMCAA8BAAIRAyEEMUEFElFhcfAGgZGhEyKxwdEHMuHxFEJSFSNiCDNyFoKSFyRDU6LCCTRjRHOy0uL/xAAbAQEBAQEBAQEBAAAAAAAAAAAAAQIDBAUGB//EACoRAQEBAQACAwADAAEEAwEBAQABEQIDcRIhMQQTsVEUIjJBBWGBwUIj/9oADAMBAAIRAxEAPwCgrFsRw4ZfWEs2FXUN4C7p4c10702ML4/M+p6jhzfqep/i4p0uS9Vtw8vddwRkX7t+ck1TdElWusVNVsRY3K1ngx2YFsz5rMYytJHX+7rSeDWGf6XHqf8A0938eZ02zK8LlWoMzwP9LwCV2jxC81j7kswTAYsE2Xto1OAzVPslvzHT8K8LV

这是我的控制器和我的代码:

@PostMapping(value = "/saveBlueprintOrder")
public ResponseEntity<?> saveBlueprintOrder(@RequestParam MultipartFile blueprint,
                                            @RequestParam(required = false) MultipartFile coversheet,
                                            @RequestParam(required = false) MultipartFile logo,
                                            @ModelAttribute BlueprintOrder blueprintOrder) { 


if(coversheet != null) {

           BASE64Decoder decoder1 = new BASE64Decoder();
           byte[] imageBytes = decoder1.decodeBuffer(coversheet.getInputStream());
           InputStream bis = new ByteArrayInputStream(imageBytes);
           BufferedImage image = ImageIO.read(bis);
           ImageIO.write(image, "jpg", new File("C:\Users\i58287\Downloads\coversheet.jpg"));


            OutputStream stream = new FileOutputStream("C:\Users\i58287\Downloads\coversheet-test.jpg");
            stream.write(imageBytes);
            stream.close();

我只需要能够将此图像转换为输入流,这样我就可以在本地检查图像,此外我还需要将其发送到另一个 api。我错过了什么导致这张图片无法打开?感谢您的帮助!

PS:我做了很多组合,所以这显示了我尝试过的几个选项,BufferedImage image = ImageIO.read(bis) 不断返回空图像。

好的,所以我不知道为什么这是我必须做的,但我最终将我的字节 [] 保存为一个字符串并切断了预先设置的

data:image/jpeg;base64

然后我把它解码成一个InputStream。有人知道我为什么要这样做吗?

代码如下:

 String imageBytes = new String(coversheet.getBytes(), StandardCharsets.UTF_8);
            String imageDataBytes = imageBytes.substring(imageBytes.indexOf(",") + 1);
            InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(imageDataBytes.getBytes()));
            BufferedImage image = ImageIO.read(stream);
            ImageIO.write(image, "jpg", new File("C:\Users\i58287\Downloads\coversheet-test.jpg"));