简体   繁体   English

如何在 Node.js 上使用模糊而不是信箱按比例调整图像大小?

[英]How do I resize an image proportionally using blur instead of letterbox on Node.js?

I have a photo which is a rectangle and I want to resize it down to a square while preserving the aspect ratio .我有一张矩形的照片,我想将其缩小为正方形,同时保留纵横比 Libraries like Sharp allow you to do that by applying letterboxing to the resulting image.Sharp这样的库允许您通过对生成的图像应用信箱来做到这一点。

await sharp(photoBuffer).resize({ width: 200, height: 200, fit: 'contain' })

This is the result:这是结果:

带信箱

Instead of applying letterboxing I'd like the remaining empty space to be filled with a 2nd blurred version of the image, placed behind the resized one, like so:而不是应用信箱,我希望剩余的空白空间填充图像的第二个模糊版本,放置在调整大小的图像后面,如下所示:

例子

Is there a Node.js library that does that out of the box or some custom way of achieving this?是否有开箱即用的 Node.js 库或实现此目的的某种自定义方式?

This is how you do it using Sharp:这是使用 Sharp 的方法:

import Sharp from 'sharp'

export default function({ pathToInputFile, pathToOutputFile, size, blur }) {
  let sharpOriginal = Sharp(pathToInputFile)
  
  return new Promise((resolve) => {
    sharpOriginal
      .resize({ width: size }) // the result will be a square
      .toBuffer()
      .then((blurredAsBuffer) => {
        sharpOriginal
          .resize(size, size, {
            fit: 'cover'
          })
          .blur(blur) // blur = 6 seems to work well
          .composite([{
            input: blurredAsBuffer,
            gravity: 'center'
          }])
          .toFile(pathToOutputFile)
          .then((info) => {
            console.log(info)
            resolve(true)
          })
          .catch((err) => {
            console.error(err))
            resolve(false)
          })
      })
      .catch((err) => {
        console.error(err))
        resolve(false)
      })
}

You can try look into filter 's blur function.您可以尝试查看过滤器blur function。

You can also use SVG filter for more options您也可以使用SVG滤波器以获得更多选项

Here's an example: https://css-tricks.com/the-blur-up-technique-for-loading-background-images/这是一个示例: https://css-tricks.com/the-blur-up-technique-for-loading-background-images/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM