如何使用Javascript从给定的URL下载GIF [英] How to download a GIF from a given URL using Javascript

查看:80
本文介绍了如何使用Javascript从给定的URL下载GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Giphy 下载GIF (只需要下载它,就不需要在浏览器中显示它了).

I am trying to download a GIF from Giphy (just need to download it, I don't need to display it on the browser).

我尝试使用此问题中的解决方案此问题但是它会下载静态图片:

I tried using the solution in this question this question however it downloads a static image:

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 = 'giphy.gif'; // or define your own name. 
        tempbtn.click();
        tempbtn.remove(); 
    };
}

<a href="#" onclick="download_img(this,'https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif')"  > Descargar gif </a>

我还想知道为什么需要创建一个 new Image(); 并创建一个 canvas标签

I also wonder why it's needed to create a new Image(); and create a canvas tag

推荐答案

这对我有用,我从这里获取了一些代码 https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/

This works for me, I took some of the code from here https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/

(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();
})();

这篇关于如何使用Javascript从给定的URL下载GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆