在SailsJS上使用Sharps在Sails-hook-uploads中调整图像大小

时间:2019-07-14 13:11:25

标签: javascript node.js image-processing sails.js sharp

我正在尝试使用sailsJS使用Sharp调整图像大小。

我尝试了以下。 https://malcoded.com/posts/nodejs-image-resize-express-sharp/ 和.. https://github.com/firebase/functions-samples/blob/master/image-sharp/functions/index.js

我不确定是否要输入正确的文件格式。我知道它会接收实际的图像文件或流对象,并且我已经尝试了各种组合,但目前都没有成功。

摘自Sharp文档:
谁能启发我writableStream的来源?图像流还会插入哪里?

 // from Sharp documentation https://sharp.pixelplumbing.com/en/stable/api-resize/
 const transformer = sharp() 
  .resize({
    width: 200,
    height: 200,
    fit: sharp.fit.cover,
    position: sharp.strategy.entropy
  });
// Read image data from readableStream
// Write 200px square auto-cropped image data to writableStream
readableStream
  .pipe(transformer)
  .pipe(writableStream); // where is writable stream from? and where does one plug in the image upstream?  

我的代码:

当我在图像上使用typeof进行验证时,它将返回object。我正在使用sails-hook-uploads https://www.npmjs.com/package/sails-hook-uploads,并且按需传递图像对象。但是,一旦我添加了Sharp,那就是另一回事了。

    module.exports = {
      description: "Make a new post",
      files: ["image"], 

      inputs: {
        image: {
        description: "Upstream for an incoming file upload.",
        type: "ref"
       }, // ......

  fn: async function({ image, title }) {

  console.log(typeof image) // returns object but its an upstream object. (uploading also works when plugged into sails.uploadOne())

    var sharp = require('sharp');

    var transform = sharp().rotate(180) 
    image.pipe(transform) //Isn't image already a stream?


   // Upload the image.
    var info = await sails
      .uploadOne(image, { 
        maxBytes: 3000000
      })
      .intercept("E_EXCEEDS_UPLOAD_LIMIT", "tooBig")
      .intercept(
        err => new Error("The image upload failed: " + util.inspect(err))
  );

但是,出现此错误

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object

我也尝试过组合,正好是主要部分的实现方式。

    sharp('image').rotate(180).toBuffer()
  .then(function (data) {
    console.log(data)
    console.log(sharp(data).metadata())
    return [data, sharp(data).metadata()];
  })

但是我收到此错误消息。

(node:99902) UnhandledPromiseRejectionWarning: Error: Input file is missing
(node:99902) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

我的猜测是,以这种方式使用时不会吸收流,因此可以追溯到第一种使用.pipe()的实现样式。

我的意图是将图像插入上游以使其清晰,然后返回另一个上游,然后可以将其传递到sails.uploadOne中。我希望外面有人能给我启发,如果我正确使用Sharp的话。

可能缺少关于Sharp或Fs的步骤。我最好的猜测是在createReadStream()上,我不确定是否应该导入fs并使用它。.因为“图像”已经存在上游,并且我需要插入上游端以sails.uploadOne()才能工作。夏普也接受上游。.我希望我可以在中间插入夏普。

希望有人提出任何建议或可以将我的头指向正确的方向...

提前感谢大家,祝您有个美好的一天!

0 个答案:

没有答案
相关问题