Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 653
stckoverflowaccnt12 Avatar asked Apr 24 '17 15:04

stckoverflowaccnt12


People also ask

Can we convert image to Base64?

Convert Images to Base64 Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!


1 Answers

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…

like image 189
EmmanuelBeziat Avatar answered Oct 11 '22 19:10

EmmanuelBeziat