One-click download button for a giphy gif - html

I want to create a one-click download link for images. I get inconsistent results with the html5 download attribute.
W3 schools has a working example triggering a download: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download
When I change the image urls to anything else it does not trigger a file download.
For example this code doesn't trigger a download:
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" download>
Can anyone explain why?

I asked the same question, here is the code that worked for me:
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();

In the w3schools example that you have attached, the link text which you should click on to start download is an image. They have put an image inside of an anchor tag (<a></a>) and then have given URL to the href attr of the anchor. Then if you change the href, the url will change without changing the image and you can start downloading by clicking on the image.
in the code that you have attached to your question (Which is working and download an image as a file if you add the </a> to the end of it.), you've given the URL of an image as href attr. So if you change the href, different file would be downloaded.
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" download>click</a>
if you want to click on your image to start the download, you should put an image inside of the anchor and then gave the href attr, your file URL.
<a href="" download>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" alt="image" width="100" />
</a>

The problem of why it's not working is that the download attribute only works for same-origin URLs. You can find the details here MDN Docs
As for an alternative, you can use some javascript like this to achieve the same.
function download_img(e,link){
var image = new Image();
image.crossOrigin = "anonymous";
image.src = link;
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
tempbtn = document.createElement('a');
tempbtn.href = blob;
tempbtn.download = 'image.jpg'; // or define your own name.
tempbtn.click();
tempbtn.remove();
};
}
<!DOCTYPE html>
<html>
<body>
<a href="#" onclick="download_img(this,'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg')" >Download image
</a>
<p><b>Note:</b> The download attribute is not supported in Edge version 12, IE, Safari 10 (and earlier), or Opera version 12 (and earlier).</p>
</body>
</html>

Related

converting image and video data uri to base 64

I was trying to encrypt image and video src by converting into base 64 encoded value. I had taken reference from https://www.iandevlin.com/blog/2012/09/html5/html5-media-and-data-uri
Following is my html code:
<!DOCTYPE html>
<html>
<body>
<video style="width: 640px; height: 360px;" onloadstart="" id="mediaplayer" oncontextmenu="return false;" controls preload src="" poster=""/>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script>
// To access player after its creation through jQuery use:
var videoSrc = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4';
var imageSrc = 'http://www.w3schools.com/images/w3html5.gif';
var playerObj = $('#mediaplayer')[0];
var encodedSrc = btoa(playerObj.src);
var decodedSrc = atob(encodedSrc);
var playerObjPoster = playerObj.poster;
console.log(decodedSrc);
playerObj.src = "data:video/mp4;base64,"+btoa(videoSrc);
//playerObj.src = videoSrc;
playerObj.poster = 'data:image/gif;base64,'+btoa(imageSrc);
//playerObj.poster = imageSrc;
</script>
</html>
On runtime image and video src is showing as encoded value but neither image and neither video is displayed on the web page.
Any suggesstions ?
It does not work like this. You must base64 encode the actual contents of the file, not the path to the file. The link you used actually shows this in the example:
function getEncodedVideoString($type, $file) {
return 'data:video/' . $type . ';base64,' . base64_encode(file_get_contents($file));
}
Currently what is happening is that the browser is trying to use the decoded value (whis is a URI) as the actual image or video data and of course it fails.

chrome extension: Parse JSON data and get image

i have a json data like that
{ "ikealogo": "https://xxx.blob.core.windows.net/logo/24536.jpg?v=20120912144845" }
how can i convert it in image view?
Things i have tried but need alternate solution. it works fine in popup window but **i need to convert it for my content script in a specific webpage, when user will hover mouse on a text and should appear this image ** but applying same process is not working at all.
//popup.js
var image = document.getElementById('img');
image.src = jsonData.ikea.ikealogo;
//popup.html
<img id="img" />
SOLUTION:
To appear any image from external server on DOM :
I parse data from API response and create div with jquery and append the image data inside it.
There's NO need for CROSS DOMAIN COMPLICITY.
var image= data["company"].ikealogo;
var div=jQuery('<div/>',
{
"class": "divC",
});
var i = jQuery('<img />').error(function()
{
this.src = default_image;
}).attr('src', image)
.css({ "width":"50px", "height": "50px","margin": "0px 10px 10px 10px"});
div.append(i)

Download attribute for downloading an HTML file of a div outputs an file with the HTML in one contiguous line.

I am using the HTML5 download attribute to download the HTML of a particular div:
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "export.html";
a.href = "data:text/attachment," + document.getElementById("export").innerHTML;
a.innerHTML = "[Export content]";
This works but the HTML file comes out in one continuous line:
<tr><td><p>ADL</p></td><td><p>Some text here.</p></td><td></td></tr><tr><td><p>...
Any ideas?
I was able to fix this by changing my href to the following:
a.href = "data:text/plain;charset=utf-8," + encodeURIComponent(code);

How to download image object on page as a file in html?

I am creating an image dynamically on the page using dataURL,
var aImg = document.createElement('img');
aImg.setAttribute('src', dataURL);
aImg.setAttribute('alt', 'pic');
aImg.setAttribute('width', '438px');
aImg.setAttribute('height', '267px');
aImg.onclick = (function() {
//download the image object
})();
I am not sure what to do to download this image object that is a PNG image.
Can someone give hints?
If you want the image to be displayed the follwing should be fine :
aImg.src = YOUR_URL
if you want to save it on to the file , you shoud redirect and let the browser take care of the rest. JS redirect can be done as follows :
window.location.replace(dataURL)
If you want the browser to give a pop-up saying "Save File" check out this link : http://muaz-khan.blogspot.in/2012/10/save-files-on-disk-using-javascript-or.html

Storing HTML5 canvas containing images

How do you store a canvas that contains images using the toDataURL method? Everything works fine for text and drawing, but I don't know how to handle images. Any help would be appreciated. Thanks
I have modified my question as follows:
This works when the image is pulled directly from a .png. However, when I call the Google Charts API, toDataURL doesn't work even though the image renders correctly on the canvas. Google Charts is returning a .png. Anyone have any ideas? Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8">
function test() {
var c = document.getElementById("drawing-canvas");
var cxt = c.getContext("2d");
// This doesn't work.
//var imgsrc = 'http://chart.apis.google.com/chart?cht=tx&chf=bg,s,ffffff&chco=000000&
chl=a';
// This works
var imgsrc = 'chart.png';
var img = new Image();
img.src = imgsrc;
cxt.drawImage(img,0,0);
}
function wr() {
var cc = document.getElementById("drawing-canvas");
var url = cc.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
</script>
</head>
<body onload = "test();">
<canvas id="drawing-canvas" width = "500px" height = "500px" style="background-color:
#ffffff; border: 2px solid #000000;">
Your browser does not support the canvas element.
</canvas>
<input type = "button" value = "go" onclick = "wr();">
</body>
</html>
First of all, your chart didn't even render on the canvas when I tested it. You need to wait for the image to load. Your chart.png image probably loads instantaneously since it's cached, but the one generated by Google Charts API isn't. This is what you should do:
var img = new Image();
img.onload = function()
{
cxt.drawImage(img,0,0);
}
img.src = imgsrc;
Aside from that, you must be getting a SECURITY_ERR in your browser's console. This is because the Canvas security model doesn't allow you to export images coming from an external URL. You should use a server-side language to save the Google Charts image to your server, then load it from there.
The HTML canvas element has a method called toDataURL, that will return a data URL image representing the canvas. You can check the documentation API on the MDN.
Specifically, it says about toDataURL:
toDataURL(in optional DOMString type, in any ...args)
returns DOMString
Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG).
If the height or width of the canvas is 0, "data:," representing the empty string, is returned.
If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.
Chrome supports the image/webp type.
If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.
And provides and example on how to use it:
function test() {
var canvas = document.getElementById("canvas");
var url = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
In this example, we use the dataURL as the source attribute of an img element, but you can do whatever you want you it (like storing it somewhere, or sending it to the server with an ajax call).
Note that most of the methods involved in drawing on canvas are methods of drawing context (obtained by a call to getContext), while this method is one of the canvas element.