简体   繁体   English

如何在javascript中调整Base64图像的大小

[英]how to resize Base64 image in javascript

I tested this package: https://preview.npmjs.com/package/resize-base64 我测试了这个软件包: https//preview.npmjs.com/package/resize-base64

it requires a front-end part to make Canvas element .. and so on, I only need to make this process without front-end 它需要一个前端部分来制作Canvas元素..依此类推,我只需要在没有前端的情况下进行这个过程

I use react native, so any solution for React/Native, node, or native javascript is acceptable. 我使用react native,因此任何React / Native,node或native javascript的解决方案都是可以接受的。

its maybe late, but hope to help the others. 它可能很晚,但希望能帮助其他人。

const sharp = require('sharp');

// original base64 image
const base64Image = "data:image/jpeg;base64,/9j/4QDsRXhpZg ...  ...  ... ";

// express route function
export default function (req, res, next) {
    let parts = base64Image.split(';');
    let mimType = parts[0].split(':')[1];
    let imageData = parts[1].split(',')[1];

    var img = new Buffer(imageData, 'base64');
    sharp(img)
        .resize(64, 64)
        .toBuffer()
        .then(resizedImageBuffer => {
            let resizedImageData = resizedImageBuffer.toString('base64');
            let resizedBase64 = `data:${mimType};base64,${resizedImageData}`;
            res.send(resizedBase64);
        })
        .catch(error => {
            // error handeling
            res.send(error)
        })
}

You have to do this in steps: 您必须按步骤执行此操作:

  1. Decode the Base64 解码Base64
  2. Decode the image data 解码图像数据
  3. Scale the image 缩放图像
  4. Encode the image 编码图像
  5. Output the image 输出图像

Almost all of these steps can be done with Sharp. 几乎所有这些步骤都可以通过Sharp完成。 https://github.com/lovell/sharp This package uses libvips and is significantly faster than any other image scaler in most cases. https://github.com/lovell/sharp此软件包使用libvips并且在大多数情况下明显快于任何其他图像缩放器。

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

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