【问题标题】:display an <Image> in react native using the content of the image and not the path使用图像的内容而不是路径在本机反应中显示 <Image>
【发布时间】:2020-06-16 19:41:09
【问题描述】:

我正在尝试使用来自react-native&lt;Image/&gt; 显示图像。端点是用 Spring 构建的,并将图像内容写入输出流。端点接收图像 ID。

如果我执行 Postman 的请求,结果我可以看到图像。

我想寻找解决方案,我认为这是我设法得到的最接近的解决方案https://stackoverflow.com/a/44058739/869793

我在文档中看到它可以通过使用 base64 编码响应来工作,但我还没有到达那里,我希望没有它我可以让它工作。

 useEffect(() => {
    axios.get(
      'http://localhost/images/id15', 
      {responseType: 'arraybuffer'}
    )
    .then(resp => {
      const data = Buffer.from(resp.data, 'binary').toString('base64')
      console.log("resp => " + data);
      let imageUri = "data:image/jpeg;base64," + data;
      setSource({uri: imageUri})
    })
  }, []) 


<Image
  style={styles.tinyLogo}
  source={source}
/>

我通过混合不同的参数在日志中得到输出。没有显示图像。

 LOG  resp => ����
 LOG  resp => 77+977+977+977+9
 LOG  resp => /f39/Q==

【问题讨论】:

    标签: reactjs spring react-native axios


    【解决方案1】:

    我最终创建了一个检索编码图像的端点。

    弹簧代码:

    @GetMapping("/encoded-base64/{id}")
    public Map<String, String> retrieveBase64EncodedImage(@PathVariable UUID id) {
        return singletonMap("data", imageService.findByIdAndEncode(id));
    }
    
    public String findByIdAndEncode(UUID id) {
        Image image = imageRepository.findById(id).orElseThrow();
        InputStream inputStream = storageService.get(image.getFilePath());
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            throw new RuntimeException("Cannot copy stream", e);
        }
    }
    

    React Native 代码:

      useEffect(() => {
        axios.getAsync(
          'path_to_server/encoded-base64/37d1302d-3ba2-4b4e-b08d-5323979abf38', 
        )
        .then(resp => {
          const data = resp.data.data
          console.log("resp => " + JSON.stringify(data));
          let imageUri = "data:image/jpeg;base64," + data;
          setSource({uri: imageUri})
        }) 
      }, []) 
    
    
      <Image
        style={styles.tinyLogo}
        source={source}
      />
    

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 2017-03-14
      • 2016-08-02
      • 2020-11-30
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多