簡體   English   中英

使用 node.js 從 URL 讀取圖像

[英]Read images with node.js from URL

請原諒我對節點的無知。

我需要通過 url 讀取圖像並通過銳化調整其大小。

目前我有這樣的閱讀本地。

例如。 我想閱讀這張圖片 url="https://miami.pfsrealty.com/wp-content/uploads/2020/02/Miami-y-su-bahia-con-nubes-al-atardecer-Compressed.jpg"

我目前的代碼是這樣的。

return new Promise(async (resolve, reject) => { const fileSystem = require('fs');

        const image = fileSystem.readFileSync(directoryPath, 'base64');
          const sharp =  require('sharp');
          const height: number = parseInt(heightString);//parameter
          const width: number = parseInt(widthString);//parameter
            let img = new Buffer(image, 'base64');
            await sharp(img)
                .resize(height, width)
                .toBuffer()
                .then(resizedImageBuffer => {
                    const resizedImageData = resizedImageBuffer.toString('base64');
                    resolve(resizedImageData);
                })
                .catch(error => {
                    // error handeling
                    reject(error);
                });
        });

應該怎么打電話? 謝謝 !

嘗試這個


const sharp = require('sharp');
const fs = require('fs');

function readAndSave(url, width = 300, height = 300) {

    const filename = url.replace(/^.*[\\\/]/, '');

    require('axios').get(url, { responseType: 'arraybuffer' })
        .then((response) => {
            return Buffer.from(response.data, "utf-8")
        }).then((buffer) => {
            return new Promise((resolve, reject) => {
                sharp(buffer)
                    .resize(height, width)
                    .toBuffer()
                    .then(resizedImageBuffer => {
                        const resizedImageData = resizedImageBuffer.toString('base64');

                        const buf = Buffer.from(resizedImageData, 'base64');

                        fs.writeFile(`./${filename}`, buf, function (err) {
                            if (err) throw err;
                        });
                        resolve()
                    })
                    .catch(error => {
                        // error handeling
                        reject(error);
                    });
            })

        }).catch(error => {
            console.log('error', error)
        });





}

readAndSave('https://miami.pfsrealty.com/wp-content/uploads/2020/02/Miami-y-su-bahia-con-nubes-al-atardecer-Compressed.jpg');

暫無
暫無

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

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