2017-03-27 89 views
-1

在我的node.js項目中,我希望能夠從網絡中拉出圖像,將它們調整到我想要的大小,然後以base64字符串形式輸出。在服務器大小上調整圖像大小

哪個庫是做這件事的最好方法? 我嘗試了很多不同的人,但他們都不工作:

var url = "www.abc.com/image.png" 

var gm = require('gm') 

gm(request(url)) 
.resize(100, 100) 
.setFormat('jpg') 
.toBuffer(function (err, buffer) { 
    if (err) { 
    console.log("error" + err); 
    } else { 
    console.log('done!'); 
    } 
}) 

var Canvas = require('canvas') 
    , Image = Canvas.Image 
    , canvas = new Canvas(200, 200) 
    , ctx = canvas.getContext('2d'); 

// set its dimension to target size 
canvas.width = width; 
canvas.height = height; 

// draw source image into the off-screen canvas: 
ctx.drawImage(request(url), 0, 0, width, height); 

console.log(canvas.toDataURL()); 

sharp('input.gif') 
    .resize(478, 269) 
    .toFormat('jpeg') 
    .toBuffer(function(err, outputBuffer) { 
    if (err) { 
     throw err; 
    } 
    // outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high 
    // containing a scaled version, embedded on a transparent canvas, of input.gif 
}); 



require('lwip').open(request(url), function(err, image){ 
    image.resize(300, 200, function(err, image){ 
     console.log("done"); 
    }); 
}); 


var request = require('request'); 
var lwip = require('lwip'); 
request({url: url, encoding:null}, function (err, response, imageBuffer) { 
    var imageFormat = response.headers["content-type"].match(/(png|jpg|jpeg)/)[0]; 
     lwip.open(imageBuffer, imageFormat, function(err, image){ 
      if (err || !image) throw err; 
      image.resize(196, 196, function(err, image){ 
       if (err || !image) throw err; 
       image.toBuffer(imageFormat, function(err, buffer){ 
        //here you buffer you can save image in file with FS 
       }); 
      }); 
     }); 
    } 
}); 
+0

gm是一個很好的lib –

+0

我的代碼有什麼問題,然後 –

回答

0

這是有點不同的方法 這是咖啡的腳本,所以你需要爲正常的JavaScript 首先下載圖像從服務器 改變它然後調整圖像如下

gm downloadedFile.path 
    .resize 100, 100 
    # thumbpath is resized file storage path 
    .write thumbpath, (err) => 
    if err 
     console.log err 
    #convert as base64 
    bitmap = fs.readFileSync(thumbpath) 
    base64 = new Buffer(bitmap).toString('base64')