How do I convert a base64 string formatted image to the datatype sharp image downsizer expects?
Asked Answered
D

2

23

I'm trying to downsample an image in node. I have that image stored as a base64 encoded string (ie: "data:image/png;base64,iVBOR" etc.). I'm using Sharp npm package. The documentation appears to delineate that sharp can take either the filepath to an image or an "inputBuffer." I did some googling and assume the Buffer class is what they are referring to. Trying the code below among others continuously has resulted in me receiving the following error: "Input buffer contains unsupported image format." What could my issue be, and if you're not sure could you please recommend me a different npm package with more clear documentation?

 const downsizeProfileImgForTweet = (user, cb) => {
        let imgBuffer =  Buffer.from(user.profileImg, 'base64');
        sharp(imgBuffer)
        .resize(52, 52)
        .toBuffer()
        .then(data => {
            console.log("success");
            user.profileImg = data;
            cb()
        } )
        .catch( err => console.log(`downisze issue ${err}`) );
    }

I looked all over the internet and did a bunch of guess and checks, so forgive me for the noob question. Thanks in advance for any help you can offer!

Doolittle answered 24/4, 2017 at 15:30 Comment(1)
In other words to a bufferDoolittle
R
22

You need to remove the "data:image/png;base64" part.

So here you are:

const uri = user.profileImg.split(';base64,').pop()
const downsizeProfileImgForTweet = (user, cb) => {
    let imgBuffer = Buffer.from(uri, 'base64');
    sharp(imgBuffer)
    .resize(52, 52)
    .toBuffer()
    .then(data => {
        console.log('success')
        user.profileImg = data
        cb()
    })
    .catch(err => console.log(`downisze issue ${err}`))
}

Not sure if it will work with the ".toBuffer() method, though it works like this for me (to write the file):

sharp(imgBuffer)
    .resize(1920, null)
    .toFile(`${config.images_path}/${picture.filename}`)
    .then(data => {
        console.log('normal: ', data)
    })
    .catch(err => console.log(`downisze issue ${err}`))

I was struggling with this not so long ago…

Rotter answered 21/8, 2018 at 23:26 Comment(0)
C
1

Try this?

const buf = new Buffer(img.replace(/^data:image/\w+;base64,/, ""),'base64')

Coke answered 25/7, 2018 at 6:41 Comment(1)
Since node 6, it's deprecated to use a constructor with BufferRotter

© 2022 - 2024 — McMap. All rights reserved.