0

我想利用Firebase的云端功能调整上传图片的大小并覆盖原件,因此每次上传只有一个图片。Firebase的云端函数用于上传图片并调整到新宽度

此外,我不希望创建具有指定宽度和高度的图像,而是希望ImageMagick根据给定的宽度(例如800px)来调整大小。

我已经看过Firebase ImageMagick示例,以创建上传时的缩略图作为开始,但我没有看到如何修改它以满足此需求。我非常感谢一个如何实现这个目标的例子。

编辑:这是我从火力地堡的例子使用的代码的肉(https://github.com/firebase/functions-samples/blob/master/quickstarts/thumbnails/functions/index.js

// Download file from bucket. 
const bucket = gcs.bucket(fileBucket); 
const tempFilePath = `/tmp/${fileName}`; 
return bucket.file(filePath).download({ 
    destination: tempFilePath 
}).then(() => { 
    console.log('Image downloaded locally to', tempFilePath); 
    // Generate a thumbnail using ImageMagick. 
    return spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]).then(() => { 
    console.log('Thumbnail created at', tempFilePath); 
    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. 
    const thumbFilePath = filePath.replace(/(\/)?([^\/]*)$/, '$1thumb_$2'); 
    // Uploading the thumbnail. 
    return bucket.upload(tempFilePath, { 
     destination: thumbFilePath 
    }); 
    }); 
}); 

回答

0

在ImageMagick的,您可以通过

convert inputimage -resize 800x outputimage 

做到这一点,而不只是指定的高度,宽度为800和“x”,它会将宽度转换为800,并使宽高比保持不变。

对不起,我不知道Firebase。

+0

感谢您的回复。我将我正在使用的代码添加到原始问题中。我看到我会用800x的建议替换200x200。此外,它看起来像我需要交换“-thumbnail”和“-resize”。我仍然无法用新调整大小的图像覆盖原始图像。 – Playgraph

+1

为输出图像指定一些其他现有目录的路径 – fmw42

1

可以使用自定义的元数据,而不是“thumb_”前缀,以避免功能循环,当你用缩略图覆盖原文件路径:

const filePath = event.data.name 
const metadata = event.data.metadata 

if (metadata.isThumb) { 
    console.log('Exiting: Already a thumbnail') 
    return 
} 

你只需要后spawn完成调整设置它:

return spawn(/* ... */) 
}).then(_ => { 
    metadata.isThumb = true    // We add custom metadata 
    const options = { 
     destination: filePath,   // Destination is the same as original 
     metadata: { metadata: metadata } 
    } 
    // Overwrite the original path 
    return bucket.upload(/* localThumb */, options) 
}) 
相关问题