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) 
}) 
相關問題