簡體   English   中英

使用 puppeteer 和 node.js 下載“數據:”圖像/文件

[英]Download a 'data:' image/file using puppeteer and node.js

我正在嘗試使用 node.js 和 puppeteer 下載圖像,但遇到了一些問題。 我正在使用網絡爬蟲從網站收集圖像的鏈接,然后使用 https/http package 下載圖像。

這適用於使用 http 和 https 源的圖像,但有些圖像的鏈接看起來像這樣(整個鏈接很長,所以我剪掉了其余的):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAw8AAADGCAYAAACU07w3AAAZuUlEQVR4Ae3df4yU930n8Pcslu1I1PU17okdO1cLrTD+g8rNcvRyti6247K5NG5S5HOl5hA2uZ7du6RJEGYPTFy1Nv4RUJy0cWVkeQ9ErqqriHNrR8niZuVIbntBS886rBZWCGHVsNEFRQ5BloPCzGn2B+yzZMLyaP........

我不確定如何處理這些鏈接或如何下載圖像。 任何幫助,將不勝感激。

您需要首先使用 node.js Buffer從 base64 解碼 url 。

// the content type image/png has to be removed first
const data = 'iVBORw0KGgoAAAANSUhEUgAAAw8AAADGCAYAAACU07w3AAAZuUlEQVR4Ae3df4yU930n8Pcslu1I1PU17okdO1cLrTD+g8rNcvRyti6247K5NG5S5HOl5hA2uZ7du6RJEGYPTFy1Nv4RUJy0cWVkeQ9ErqqriHNrR8niZuVIbntBS886rBZWCGHVsNEFRQ5BloPCzGn2B+yzZMLyaP';
const buffer = new Buffer(data);
const base64data = buff.toString('base64');

// after this you will get the url string and continue to fetch the image

這些是 base64 編碼圖像(主要用於圖標和小圖像)。

你可以忽略它。

 if(url.startsWith('data:')){
   //base 64 image
 } else{
   // an image url
 }

如果你真的想搞亂 base64 我可以給你一個解決方法。

import { parseDataURI } from 'dauria';
import mimeTypes from 'mime-types';

const fileContent = parseDataURI(file);
 // you probably need an extension for that image.
let ext = mimeTypes.extension(fileContent.MIME) || 'bin';

fs.writeFile("a random file"+"."+ext, fileContent.buffer, function (err) {
    console.log(err); // writes out file without error, but it's not a valid image
});



暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM