【问题标题】:Resize image before uploading to google cloud using node js sharp在使用节点 js sharp 上传到谷歌云之前调整图像大小
【发布时间】:2022-11-21 18:53:13
【问题描述】:

我正在编写有关将图像上传到谷歌云的功能的代码。我可以将图片上传到 gcloud 但无法在上传前调整它的大小。我尝试使用 node js sharp library 来调整大小但无法正确实现它。下面是我的代码:

我的上传功能

const processFile = require('../middleware/upload')
const { format } = require('util')
const { Storage } = require('@google-cloud/storage')
// Instantiate a storage client with credentials
const storage = new Storage({ keyFilename: 'xxxxx.json' })
const bucket = storage.bucket('<---bucket name--->')

const upload = async (req, res) => {
    try {
        await processFile(req, res)

        if (!req.file) {
            return res.status(400).send({ message: 'Please upload a file!' })
        }

        // Create a new blob in the bucket and upload the file data.
        const blob = bucket.file(req.file.originalname.replace(/ /g, "_"))
        const blobStream = blob.createWriteStream({
            resumable: false,
        })

        blobStream.on('error', (err) => {
            res.status(500).send({ message: err.message })
        })

        blobStream.on('finish', async (data) => {
            // Create URL for directly file access via HTTP.
            const publicUrl = format(
                `https://storage.googleapis.com/${bucket.name}/${blob.name}`,
            )

            try {
                // Make the file public
                await bucket.file(req.file.originalname).makePublic()
            } catch {
                return res.status(500).send({
                    message: `Uploaded the file successfully: ${req.file.originalname}, but public access is denied!`,
                    url: publicUrl,
                })
            }

            res.status(200).send({
                message: 'Uploaded the file successfully: ' + req.file.originalname,
                url: publicUrl,
            })
        })

        blobStream.end(req.file.buffer)
    } catch (err) {
        if (err.code == "LIMIT_FILE_SIZE") {
            return res.status(500).send({
              message: "File size cannot be larger than 2MB!",
            });
        }
        res.status(500).send({
            message: `Could not upload the file: ${req.file.originalname}. ${err}`,
        })
    }
}

module.exports = {
  upload
}

我的 Multer 库

const processFile = require('../middleware/upload')

const util = require("util");
const Multer = require("multer");
const maxSize = 2 * 1024 * 1024;

let processFile = Multer({
    storage: Multer.memoryStorage(),
    limits: { fileSize: maxSize },
}).single("file");

let processFileMiddleware = util.promisify(processFile);
module.exports = processFileMiddleware;

上面的代码能够将图像推送到 gcloud。有人可以建议如何使用 node js sharp 调整它的大小并上传到 gcloud。先感谢您

【问题讨论】:

标签: javascript node.js google-api-nodejs-client sharp


【解决方案1】:

当您使用 multer 在 Nodejs 中获取您的 req 文件时,通过将该文件转换为 inputBuffer 并上传它来调整大小。

sharp(inputBuffer)
.resize(200, 200)
.toFile('ouput.jpg', function(err) {});

对于将图像转换为图像缓冲区,请点击此链接Convert Image to Image Buffer using js

有关调整大小的更多详细信息,您可以点击此链接Resizing Image in Nodejs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-25
    • 2018-09-21
    • 2013-10-03
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2011-04-16
    • 2015-12-05
    相关资源
    最近更新 更多