I want to load an image from an url into filereader in order to obtain a data url of that image. I tried to search for the solution on google but i can only find solutions to read them from the file input on a local computer.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
If you want a usable data-URI representation of the image, then I suggest to load the image in a
<img>
tag, paint it on a<canvas>
then use the.toDataURL()
method of the canvas.Otherwise, you need to use
XMLHttpRequest
to get the image blob (set theresponseType
property on the XMLHttpRequest instance and get the blob from the.response
property). Then, you can use theFileReader
API as usual.In both cases, the images have to be hosted on the same origin, or CORS must be enabled.
If your server does not support CORS, you can use a proxy that adds CORS headers. In the following example (using the second method), I'm using CORS Anywhere to get CORS headers on any image I want.
The previous code can be copy-pasted to the console, and you will see a small image with YouTube's favicon at the bottom of the page. Link to demo: http://jsfiddle.net/4Y7VP/