stckoverflowaccnt12
stckoverflowaccnt12

Reputation: 315

How do I transmute a base64 string into an input buffer?

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!

Upvotes: 0

Views: 3154

Answers (1)

mscdex
mscdex

Reputation: 106696

One issue is that the metadata ('data:image/png;base64,') in the data URI is not being stripped off before being passed to Buffer.from(), causing the image data to be corrupt. Removing the metadata first should allow the data to be decoded properly, assuming the base64 content itself is valid.

Upvotes: 2

Related Questions