0
votes

I have been working a lot lately with image manipulation in node using the sharp library and having my service return a base64 encoding of the new image. My question seems simple: does a base64 encoded image always end with ==? If not, what are the differences when dealing with jpeg/png? My understanding is that encoding should be the same regardless of the format, but this makes me think otherwise. During my testing, I decided to have a unit test to verify if the body of my response(the base64 image) ends with =. What I have found is that the test will pass if I do not crop the image by using sharp.max() to resize but keep the ratio. If I leave this off and resize to whatever height/width params I like, the test will fail. It is also worth noting that this behavior is limited to png, not jpeg.

Here is my resizing function:

const sharp = require('sharp');
const request = require('request');
const bufferRequest = request.defaults({ encoding: null });

function imgFormatter(url, args) {
    return new Promise((resolve, reject) => {
      bufferRequest.get(url, args, function (err, res, body) {
        let imgFormat = url.includes('png') ? 'png' : 'jpeg';
        let resized = (args.crop)
        ? sharp(body).resize(args.width, args.height)
        : sharp(body).resize(args.width, args.height).max()
        resized.toFormat(imgFormat)
        .toBuffer()
        .then((output) => {
          let newImage = "data:" + res.headers["content-type"] + ";base64," + new Buffer(output).toString('base64');
          console.log(newImage);
          resolve(newImage);
        })
        .catch((error) => {
          reject(error);
        })
      });
    })
}

Here is the end of the file looks like if cropped:

data:image/jpeg;base64,/9j/.....RgX7p57pbYTvawQC580N4QcJtygGGgG/SLplthgBV2KCfCgIa3wWTVA3HySPmgP//Z

Here is the image when NOT cropped:

data:image/jpeg;base64,/9j/.....4qUhXQD5S5HzQhAM8KRz80IQH//2Q==

Apologies for the snippet of examples, my base64 is so large I cannot include here. I am using https://codebeautify.org/base64-to-image-converter to test if the image is good, and I can see both generate images as expected in the correct sizing. Why does the cropped image encode to base64 not ending with ==? In case it is useful, here is the sharp library I am using: http://sharp.dimens.io/en/stable/api-resize/#max

1

1 Answers

3
votes

The = at the end isn't a terminator, it's padding:

https://en.wikipedia.org/wiki/Base64#Output_padding

So whether you see it or not depends on the size in bytes of the object you are encoding.