jmcgui05 jmcgui05 - 1 year ago 145
Node.js Question

When does a base64 encoded png image not end with '='

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
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()
.then((output) => {
let newImage = "data:" + res.headers["content-type"] + ";base64," + new Buffer(output).toString('base64');
.catch((error) => {

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


Here is the image when NOT cropped:


Apologies for the snippet of examples, my base64 is so large I cannot include here. I am using 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:

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download