Sharp: Saving Base64 format

Created on 14 Aug 2018  路  6Comments  路  Source: lovell/sharp

Excellent library!!!

Two quick questions.

1) Is there a way to savea Base64 image in a string variable as a resized image?
2) are there available option(s) to read an image file (.jpg) and overridingit by saving a resized version of it in the same directory path?

Thank you!

question

Most helpful comment

  1. You can just use Buffer#toString and pass base64:
const resizedImageBuf = await require('sharp')(pathToMyImage)
  .resize(32, 32)
  .toBuffer();

console.log(`data:image/png;base64,${resizedImageBuf.toString('base64')}`);
// data:image/png;base64,iVBORw0KGgoAAAANS...

(you need to match the Content-Type with the type of the resulting image, of course)

All 6 comments

  1. You can just use Buffer#toString and pass base64:
const resizedImageBuf = await require('sharp')(pathToMyImage)
  .resize(32, 32)
  .toBuffer();

console.log(`data:image/png;base64,${resizedImageBuf.toString('base64')}`);
// data:image/png;base64,iVBORw0KGgoAAAANS...

(you need to match the Content-Type with the type of the resulting image, of course)

  1. When using the filesystem, the output file will be opened and written to before the input file has finished reading and closed, so these cannot be the same.

Thank you to you both for helping me on this!

One more quick question in relation to the question number 1 above.

Let assume this time I have a Base64 image in a string variable and have already trimmed off the Content-Type (data:image/png). How can I save the content in this variable to a file with the .resize(32, 32) function mentioned above?

Thank you!

@sonnyk22, that sounds like a job for fs.writeFile. Something like:

const writeFileAsync = require('util').promisify(require('fs').writeFile);
const resizedImageBuf = await require('sharp')(pathToMyImage)
  .resize(32, 32)
  .toBuffer();

await writeFileAsync('outputFile.txt', resizedImageBuf.toString('base64'), 'utf-8');

fantastic! Another great solution to one of my issue. Thank you again!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaekunchoi picture jaekunchoi  路  3Comments

zilions picture zilions  路  3Comments

AVVS picture AVVS  路  3Comments

kachurovskiy picture kachurovskiy  路  3Comments

natural-law picture natural-law  路  3Comments