【问题标题】:Create data URIs on the fly?即时创建数据 URI?
【发布时间】:2011-10-21 06:48:05
【问题描述】:

是否有脚本(javascript / 客户端)。即时创建数据 URI。现在我使用在线 base64 创建者创建数据 URI。然后将该输出放入 css 文件中。但是当我改变图像时。要做很多工作。有没有可以帮我做的脚本?

【问题讨论】:

  • 实际指向它们怎么样?
  • 你可以指向图片,比如background-image: url('image.png')
  • @Dani 如果服务器需要自定义标头,则不是。

标签: javascript base64


【解决方案1】:

现代浏览器现在有很好的支持for base64 encoding and decoding。 base64字符串的解码和编码分别有两个函数:

  • atob() 解码一串base-64数据
  • btoa() 从二进制数据的“字符串”创建一个 base-64 编码的 ASCII 字符串

这让您可以轻松创建数据 uri,即

var longText = "Lorem ipsum....";
var dataUri = "data:text/plain;base64," + btoa(longText);
//a sample api expecting an uri
d3.csv(dataUri, function(parsed){

});

【讨论】:

  • 这个dataUri保存在哪里?它是临时保存在设备上以“data:text/plain;base64”开头的缓存目录中,还是在我的情况下为“data:image/jpeg;base64”? (在 react-native 中使用)
【解决方案2】:

作为您方案的完整解决方案,您可以使用fetch 获取图像的blob 表示,然后使用FileReader 将blob 转换为base64 表示

// get an image blob from url using fetch
let getImageBlob = function(url){
  return new Promise( async resolve=>{
    let resposne = await fetch( url );
    let blob = resposne.blob();
    resolve( blob );
  });
};

// convert a blob to base64
let blobToBase64 = function(blob) {
  return new Promise( resolve=>{
    let reader = new FileReader();
    reader.onload = function() {
      let dataUrl = reader.result;
      resolve(dataUrl);
    };
    reader.readAsDataURL(blob);
  });
}

// combine the previous two functions to return a base64 encode image from url
let getBase64Image = async function( url ){
  let blob = await getImageBlob( url );
  let base64 = await blobToBase64( blob );
  return base64;
}

// test time!
getBase64Image( 'http://placekitten.com/g/200/300' ).then( base64Image=> console.log( base64Image) );

【讨论】:

  • 这具有在 Safari 中工作的优势,其中 URL.createObjectURL() 在更高版本的 Safari 中存在问题。
【解决方案3】:

一种方法是为一个对象创建一个Blob,然后使用URL.createObjectURL()

let a = URL.createObjectURL(new Blob([JSON.stringify({whatever: "String..."}, null, 2)]))


console.log(a)

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2015-07-28
    相关资源
    最近更新 更多