【问题标题】:Use blob as src image使用 blob 作为 src 图像
【发布时间】:2016-09-11 06:00:43
【问题描述】:

我将图像作为 blob 存储在我的 MySQL BDD 中。
我调用我的节点 API,它使用 JQuery Ajax 返回我的 BDD 行:

$.ajax({
    url: "http://mydinners.fr:5280/partner",
    type: "GET",
    datatype: "json",
    contentType: "application/json; charset=utf-8",
    success: function(text){
        for(var i=0; i<text["message"].length; i++){
            var objurl = window.URL.createObjectURL(new Blob(text["message"][i]["partner_image"]));

            // text["message"][i]["image"] is an array of point like : [192,257,54,269,85,458,...]

            var module = "";
            module += "<img class='activator' src='"+objurl+"'>";

            $(".container .row").append(module);
        }
    }
});

objurl 值是这样的:“blob:http%3A//dev.mydinners.fr/e73c5c6f-562e-4b66-9d4e-7a4c8567532e”

但是图片是这样的:http://i.stack.imgur.com/Vhma7.png

你知道如何将我的 blob 图像从 mysql 转换为 img 吗? 谢谢。

【问题讨论】:

  • 您正在发出 GET 请求。没有请求正文来描述其内容类型。 contentType: "application/json; charset=utf-8", 在里面做什么?
  • 感谢@Quentin 帮助我,在 Google 上找到了。不是很明白我在这里做什么,你说我要删除这行吗?

标签: javascript jquery mysql ajax blob


【解决方案1】:

在创建 blob 之前,您必须将数组转换为二进制数据(使用 Uint8Array)

var binary = new Uint8Array(json.message[0].partner_image)

这有点无关紧要,但是当您使用 Uint8Array 时,这是一个工作示例,我只是选择自己的方式来获取/打印数据

fetch("http://mydinners.fr:5280/partner")
.then(res => res.json())
.then(json => {
  let binary = new Uint8Array(json.message[0].partner_image)
  let blob = new Blob([binary])
  let img = new Image()
  img.src = URL.createObjectURL(blob)
  document.body.appendChild(img)
})

【讨论】:

  • 太棒了,THX @Endless !
  • 请注意,fetch 和 es6 箭头函数 =&gt;let 在所有浏览器中都不能正常工作,所以你最好坚持你的代码;)
猜你喜欢
  • 2013-06-03
  • 2011-01-02
  • 2018-12-03
  • 1970-01-01
  • 2014-06-27
  • 2012-05-25
  • 2021-12-05
  • 2016-05-12
  • 1970-01-01
相关资源
最近更新 更多