2

我允許用戶上傳頭像,但我想在上傳頭像時調整頭像的大小。現在,gm似乎讓我在將文件重新調整大小之前先將它保存到磁盤。傳入請求進來時是否可以調整它的大小?我可以使用node-gm調整內存中的圖像大小,還是需要先保存它?

事情是這樣的:

var readStream = fs.createReadStream(req.files['profile-picture']['path']); 

gm(req.files['profile-picture']['path'], 'img.jpg') 
.write('/path/to/directory/img.jpg', function (err) { 
    if (!err) console.log('done'); 
}); 

回答

3

你可以通過管克流,並且不需要將文件保存到光盤!你甚至可以做一些操作一前一後,因爲GM-功能可鏈接(在我的例子我調整圖像大小和後記從中間裁剪(因此重力的作用)

gm(req.files['profile-picture']['path'], 'img.jpg') 
    .resize("100^", "100^") 
    .gravity('Center') 
    .crop(100, 100) 
    .stream(function (err, stdout, stderr) { 
    // do whatever you want with your output stream (stdout) here 
    }); 
+0

http.get('你的 - image-url')從磁盤抓取它,不是嗎?如果沒有,請解釋。 –

+0

啊我的錯,你不是試圖從遠程抓取,你正在上傳,應該更容易。答案: – hereandnow78

+0

這不起作用:'gm(req.files ['profile-picture'] ['path'],'img.jpg')。resize(「100 ^」,「100 ^」)。gravity '中心')。crop(100,100).stream(function(err,stdout,stderr){stdout.pipe(fs.createWriteStream('/ uploads /'+'img.jpg')); }); ' 給我下面的錯誤r: 'events.js:71 throw arguments [1]; //未處理'錯誤'事件 ^ 錯誤:ENOENT,打開'/ uploads/img.jpg'' –

相關問題