How to Generate a Data URI

馋奶兔 提交于 2019-12-10 21:33:55

问题


I recently came across Data URI scheme and was reading about it on Wikipedia.

Example code looks something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
          AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
          9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

My question is this: How do you generate the code (IE: iVBORw0KGgoAAAA...) for using on a website?

Note: I am specifically looking for how this is done with no server side scripts. But you can still post server side script ways for others who may come across this question. Also I have seen websites that will do this for you, how can I do it myself?


回答1:


Here's a cool way to do it for images when viewed in Google Chrome:

  1. Right-click the image in question and choose Inspect Element
  2. Right-click the image's URL (the cursor will turn into a hand) and choose Open link in Resources Panel
  3. Right-click the image in the Resources Panel and choose Copy image as Data URL
  4. Paste the Data URI wherever you need it



回答2:


If it's not clear from the Wikipedia article, a Data URI is just a way of shoving the entire contents of a file (say, a png) into a text link. Since many interesting types of files contain data that's not represented as text, the scheme uses the base64 encoding to represent the full spectrum of possible binary data in a textual format.

In addition, when a browser retrieves a file from a web server, the web server tells the browser what type of file it is, in the form of a MIME type. Since a data URI doesn't have a web server (or even a filename!) to identify the type of file, this information must be included in the URI.




回答3:


(I can not comment yet, so I am adding this as a new answer.)

Similar to Oran D. Lord's answer, this should work in Firefox:

  1. Open the image file in Firefox (or open a web page with the image).
  2. Right-click the image and choose "Inspect Element".
  3. In the Inspector, the image tag should now be highlighted. Right-click the image tag and and choose "Copy Image Data-URL" (even though it may not really be a URL, that is what the menu entry is currently called).
  4. Paste the Data URI wherever you need it.



回答4:


After doing some more reading I came across a website that was linked to from a site I trust. Works well and gives me the code for inserting into HTML, CSS, and the raw data. Very nice and best way I have found. Beware though that some of the sites I went to for Data URI generation were blocked due to malware by Google or AVG. This one seems okay though.



来源:https://stackoverflow.com/questions/10942312/how-to-generate-a-data-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!