最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - how to resize Base64 image in javascript - Stack Overflow

programmeradmin3浏览0评论

I tested this package:

it requires a front-end part to make Canvas element .. and so on, I only need to make this process without front-end

I use react native, so any solution for React/Native, node, or native javascript is acceptable.

I tested this package: 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

I use react native, so any solution for React/Native, node, or native javascript is acceptable.

Share Improve this question edited Jun 24, 2018 at 17:30 Gausul 2653 silver badges16 bronze badges asked Jun 24, 2018 at 13:34 27mdmo7sn27mdmo7sn 5092 gold badges6 silver badges15 bronze badges 2
  • You can try this solution or this one with javascript – galvan Commented Jun 24, 2018 at 13:39
  • what about node-canvas? – Itamar Commented Jun 24, 2018 at 13:59
Add a comment  | 

2 Answers 2

Reset to default 18

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
  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. https://github.com/lovell/sharp This package uses libvips and is significantly faster than any other image scaler in most cases.

发布评论

评论列表(0)

  1. 暂无评论