【问题标题】:Resizing image on server size根据服务器大小调整图像大小
【发布时间】:2017-08-19 19:48:20
【问题描述】:

在我的 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
                });
            });
        });
    }
});

【问题讨论】:

  • gm 是好的库之一
  • 那我的代码有什么问题

标签: javascript node.js imagemagick gm sharp


【解决方案1】:

这有点不同 这是咖啡脚本,因此您需要将其更改为普通的 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')

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2013-08-28
    • 2018-01-25
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多