【问题标题】:Getting a black image generated from a blob URL获取从 blob URL 生成的黑色图像
【发布时间】:2020-01-16 17:02:22
【问题描述】:

我正在使用库react-avatar-editor 来创建用户的个人资料图片。下面是我使用将裁剪后的图像发送到服务器的代码

const canvasScaled = this.editor.getImageScaledToCanvas(); //a canvas object
canvasScaled.toBlob((blob) => {
  this.setState({
      preview: blob
    },
    () => {
      let data = new FormData();
      const file = new File([blob], "my-image", {
        type: "image/png"
      });
      data.append("file", file);
      axios({
        method: "POST",
        data: data,
        url: "/media",
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then().catch()
    }
  );
})

但是服务器生成的图像是黑色图像。测试了许多文件,但结果相同 - 黑色图像。

我的后端服务是用 JAVA 编写的,所以我测试了后端服务是否正确处理图像,我编写了一个简单的文件选择

<input type="file" accept={"image/png"} onChange={onSelect}/>

<button onClick={() => {
        const data = new FormData();
        data.append("file", this.state.file);
        axios({
            method: "POST",
            data: data,
            url: "/media",
            headers: {
              'Content-Type': 'multipart/form-data'
            }
        }).then().catch()
}}>Send<button>

是的,服务端代码在上述POST 请求中运行良好。这意味着,我在 react-avatar-editor 处理代码中肯定写错了。

blob 导致了问题吗?在文件选择器的情况下如何发送图像? Base64 还是 blob?

更新:我注意到一张图片有一个奇怪的行为。如果我上传这个文件 这将转换为 这不是一个完整的黑色图像。颜色有点可疑。

为了检查库本身是否正在创建黑色图像,我使用canvasScaled.toDataURL("image/png") 检查它并将其用于图像中,是的,创建的画布没有问题,图像正在渲染。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    尝试data.append("file", blob); 而不调用new File。根据 MDN,

    File 对象是一种特定类型的 Blob,可以在 Blob 可以使用的任何上下文中使用。特别是,FileReader、URL.createObjectURL()、createImageBitmap() 和 XMLHttpRequest.send() 接受 Blob 和文件。

    【讨论】:

    • 最初,我只是这样做,但它给出了相同的结果。我使用File 来模仿普通的文件选择器。
    【解决方案2】:

    在定义 canvasScaled 后将其添加到第二行

    var ctx = canvasScaled.getContext("2d");
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    

    【讨论】:

    • 现在图像完全是白色的:D
    • 不应该ctx.fillRect(0, 0, canvas.width, canvas.height);ctx.fillRect(0, 0, canvasScaled.width, canvasScaled.height); 吗?
    • 也添加这个 ctx.globalCompositeOperation = 'source-over'
    • 不走运,仍然是白色图像。
    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2011-01-21
    • 1970-01-01
    相关资源
    最近更新 更多