【问题标题】:How to use base64 data in react-image-file-resizer?如何在 react-image-file-resizer 中使用 base64 数据?
【发布时间】:2020-09-24 23:02:40
【问题描述】:

我正在使用react-signature-canvas 库在我的应用程序中捕获用户签名。它以 base64 格式返回数据。我的要求是将捕获的签名调整为 96*96 分辨率,然后再将其发送到后端,为此我正在使用 react-image-file-resizer 库。但是,propsreact-image-file-resizer 需要图像路径,而我没有路径,只有 base64 数据。

我是新来的反应。请帮帮我!

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我阅读了 react-image-file-resized 的文档。除非您使用节点,否则您似乎无法做到这一点(因为如果您是,您实际上可以暂时保存它并读取然后删除)。

    我的建议是调整 Base64 图像本身的大小。 以下是您可能想要查看的一些资源:

    尤其是这段代码

    const resizeImage = (base64Str, maxWidth = 400, maxHeight = 350) => {
      return new Promise((resolve) => {
        let img = new Image()
        img.src = base64Str
        img.onload = () => {
          let canvas = document.createElement('canvas')
          const MAX_WIDTH = maxWidth
          const MAX_HEIGHT = maxHeight
          let width = img.width
          let height = img.height
    
          if (width > height) {
            if (width > MAX_WIDTH) {
              height *= MAX_WIDTH / width
              width = MAX_WIDTH
            }
          } else {
            if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height
              height = MAX_HEIGHT
            }
          }
          canvas.width = width
          canvas.height = height
          let ctx = canvas.getContext('2d')
          ctx.drawImage(img, 0, 0, width, height)
          resolve(canvas.toDataURL())
        }
      })
    }

    【讨论】:

    • 我使用了建议的代码,但出现了 Uncaught TypeError: Cannot read property 'source' of undefined at new Image (index.web.tsx:1) 之类的错误
    猜你喜欢
    • 1970-01-01
    • 2021-05-07
    • 2023-01-21
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2020-05-26
    • 2016-03-14
    相关资源
    最近更新 更多