返回

下载图片的N种方法

前端

前言

几日前,一个简单的下载图片需求让我的后端程序员大牛们纠结了好几天,最终还是要前端来解决,先前说不行的笔者最后还是可以了,所以趁此机会来总结一下下载图片究竟有多少种方法。

准备工作

首先,我们先起一个服务,使用express.js起个简单的服务:

const express = require('express');
const app = express();

app.get('/image.png', function(req, res) {
  res.sendFile(__dirname + '/image.png');
});

app.listen(3000);

然后,在浏览器中打开http://localhost:3000/image.png,即可看到图片。

方法一:使用JavaScript

我们可以使用JavaScript的fetch()方法来下载图片。该方法返回一个Promise对象,我们可以在该对象上添加.then()方法来处理下载完成后的结果。

fetch('http://localhost:3000/image.png')
  .then(response => {
    if (response.ok) {
      return response.blob();
    } else {
      throw new Error('Error downloading image.');
    }
  })
  .then(blob => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'image.png';
    a.click();
    URL.revokeObjectURL(url);
  })
  .catch(error => {
    console.error(error);
  });

方法二:使用HTML

我们也可以使用HTML的<a>标签来下载图片。该标签的href属性指定要下载的图片的URL,download属性指定下载后的文件名。

<a href="http://localhost:3000/image.png" download="image.png">Download Image</a>

方法三:使用Canvas

我们还可以使用Canvas来下载图片。首先,我们需要创建一个Canvas元素,然后使用drawImage()方法将图片绘制到Canvas上。最后,我们可以使用toDataURL()方法将Canvas的内容转换为DataURL。

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.onload = function() {
  ctx.drawImage(image, 0, 0);
  const dataURL = canvas.toDataURL('image/png');
  const a = document.createElement('a');
  a.href = dataURL;
  a.download = 'image.png';
  a.click();
};
image.src = 'http://localhost:3000/image.png';

方法四:使用AJAX

我们还可以使用AJAX来下载图片。首先,我们需要创建一个XMLHttpRequest对象,然后使用open()方法打开一个请求。接着,我们需要使用send()方法发送请求。最后,我们需要使用onload()方法来处理请求完成后的结果。

const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/image.png');
xhr.responseType = 'blob';
xhr.onload = function() {
  if (xhr.status === 200) {
    const blob = xhr.response;
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'image.png';
    a.click();
    URL.revokeObjectURL(url);
  } else {
    console.error('Error downloading image.');
  }
};
xhr.send();

方法五:使用jQuery

我们还可以使用jQuery来下载图片。jQuery是一个JavaScript库,它提供了许多有用的方法,其中包括$.ajax()方法。该方法可以用来发送AJAX请求。

$.ajax({
  url: 'http://localhost:3000/image.png',
  method: 'GET',
  dataType: 'blob',
  success: function(blob) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'image.png';
    a.click();
    URL.revokeObjectURL(url);
  },
  error: function(error) {
    console.error(error);
  }
});

方法六:使用CSS

我们还可以使用CSS来下载图片。首先,我们需要创建一个<style>元素,然后使用@font-face规则来指定要下载的图片的URL。最后,我们需要使用font-family属性来使用下载的图片。

@font-face {
  font-family: 'image';
  src: url('http://localhost:3000/image.png');
}

body {
  font-family: 'image';
}

方法七:使用PHP

我们还可以使用PHP来下载图片。首先,我们需要使用file_get_contents()函数获取图片的二进制数据。然后,我们需要使用header()函数设置HTTP头信息,指定要下载的文件名。最后,我们需要使用echo函数输出图片的二进制数据。

<?php
$image = file_get_contents('http://localhost:3000/image.png');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="image.png"');
echo $image;
?>

方法八:使用Python

我们还可以使用Python来下载图片。首先,我们需要使用requests库发送HTTP请求。然后,我们需要使用content属性获取图片的二进制数据。最后,我们需要使用open()函数打开一个文件,并使用write()方法将图片的二进制数据写入文件。

import requests

image = requests.get('http://localhost:3000/image.png').content
with open('image.png', 'wb') as f:
  f.write(image)

总结

以上八种方法都可以用来下载图片。每种方法都有自己的优缺点,您应该根据自己的需求选择合适的方法。