【问题标题】:How to properly send an Image from React to Java?如何正确地将图像从 React 发送到 Java?
【发布时间】:2021-11-09 01:05:38
【问题描述】:

我正在制作一个捕获网络摄像头图像的程序,我需要能够将它们发送到后端以进行文本检测和图像识别。

我正在使用 react 网络摄像头来截屏。组件声明如下:

    <Webcam
      mirrored="false"
      audio={false}
      screenshotFormat="image/jpeg"
      ref={props.webcam}
      style={{
        marginLeft: "auto",
        marginRight: "auto",
        display: "block",
        paddingTop: "10px",
        paddingBottom: "10px",
      }}
    />

然后,我调用webcamRef.current.getScreenshot() 将图像作为 Base64 编码。字节被发送到具有以下逻辑的 java 后端:

  var formData = new FormData();
  formData.append("file", props.image);
  formData.append("user", props.user);

  axios
    .post("http://localhost:8080/api/storeImage", formData, {
      headers: { "Content-Type": "multipart/formdata" },
    })
    .catch((err) => {
      throw err;
    });

到目前为止一切正常。当我尝试从 java 后端创建 ImageBuffer 时出现问题:

控制器:

@PostMapping("/api/storeImage")
@ResponseBody
public String storeImage(@RequestParam("file") String file, @RequestParam Long user) throws IOException, InvalidDniException {
    return service.storeImage(file, user);
}

服务:

public String storeImage(String source, Long user) throws IOException, InvalidDniException {
            byte[] decodedSource = Base64.getMimeDecoder().decode(source);
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(decoded)); <-- this returns null ...

我需要 BufferedImage 从捕获的屏幕截图中裁剪和提取信息。我在类似问题上找到的每个答案似乎在这里都不起作用。

【问题讨论】:

  • 应该是表单数据还是多部分文件?在下载中,主要使用 octetstream。 “文件”参数不应该是字节[]而不是字符串吗?
  • 好吧,当它试图从 String 转换为 Long 时,现在为您的“user”参数抛出错误。检查 @RequestParam("user") 是否应该存在
  • 好的,我们来检查每一步中图像数据的值。你能从控制器本身开始确认对象是否不为空吗?调试并告诉我。
  • 您能否分享您收到的堆栈跟踪或错误信息。我无法处理错误原因
  • 那将是非常难以调试的。你能举例说明“source”和“decodedSource”包含的内容吗?

标签: java reactjs spring base64 bufferedimage


【解决方案1】:

原来我必须从收到的字符串中删除这个前缀:data:image/jpeg;base64。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2018-01-23
  • 2020-11-20
  • 2019-05-03
  • 1970-01-01
相关资源
最近更新 更多