Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resize Base64 image in javascript

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.

like image 674
27mdmo7sn Avatar asked Jun 24 '18 13:06

27mdmo7sn


People also ask

Can you resize an image in JavaScript?

Image resizing in JavaScript - Using canvas element. The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. Resizing images in browser using canvas is relatively simple. drawImage function allows us to render and scale images on canvas element.

Does Base64 encoding reduce size of image?

Download size increase Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.

Does converting to Base64 increase size?

Encoded size increase This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase). The increase may be larger if the encoded data is small.


1 Answers

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)
        })
}
like image 185
Sadegh Teimori Avatar answered Sep 28 '22 17:09

Sadegh Teimori