88

I am making a small app in sails.js and I need to store images in database. For that, I need to convert an image to a base64-encoded data URL so that I can save it as a string in my sails models. However, I don't know how to convert it in this form. All the older questions asked about converting an image to base64-encoded data URLs, and they answer this about doing it on the client side. However, I want to do it on the server side while I will be getting the image through a post request. How can I achieve this?

1
  • What's your sever side technology?
    – Nadendla
    Jul 2, 2014 at 5:35

6 Answers 6

150

As I understand you want to convert a file into base64 encoded string. Whether the file is image or not, that does not matter.

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

Usage:

var base64str = base64_encode('kitten.jpg');

Source

4
  • 4
    fs.readFile gives a buffer if no encoding is passed, so no need for the new Buffer(). Related doc.
    – tleb
    Feb 8, 2017 at 23:57
  • 32
    Don't forget to add the data URI prefix: data:[<mediatype>][;base64], For example: data:image/png;base64, in case of a PNG image. More info: Data URIs on MDN Jun 2, 2017 at 14:53
  • 26
    new Buffer() is deprecated. You can use instead fs.readFileSync(file, { encoding: 'base64' });
    – Idan Dagan
    Jan 11, 2018 at 8:27
  • base64 encoded only is free, but to create a dataURI, some kind of mime-db is required. npmjs.com/package/mime-types
    – Polv
    Sep 28, 2020 at 11:32
114

It can be achieved with readFileSync, passing in the image path as the first parameter and an encoding option as the second. As show below:

var fs = require('fs');

var imageAsBase64 = fs.readFileSync('./your-image.png', 'base64');

As per the node documentation:

fs.readFileSync(path[, options])

Synchronous version of fs.readFile(). Returns the contents of the path.

If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

4
  • @JSON-C11 Why not use the async version of this? Jun 27, 2019 at 7:07
  • I am trying to use it in angular and getting an error: Module not found: Error: Can't resolve 'fs'
    – GhostDede
    Nov 10, 2020 at 7:27
  • 1
    what if I have a URL instead of a file... Feb 13, 2022 at 14:24
  • 3
    you can also import a promisify version of fs like this import fs from 'fs/promises';
    – wald3
    Feb 22, 2022 at 16:33
1

//You can use the image-to-base64

const imageToBase64 = require('image-to-base64');

imageToBase64("URL") // insert image url here. 
    .then( (response) => {
          console.log(response);  // the response will be the string base64.
      }
    )
    .catch(
        (error) => {
            console.log(error);
        }
    )
0
1

Another solution to use the Buffer.from

  1. ES6 version
import fs from 'node:fs';

const convertImageToBase64URL = (filename, imageType = 'png') => {
  try {
    const buffer = fs.readFileSync(filename);
    const base64String = Buffer.from(buffer).toString('base64');
    // console.log(`base64String`, base64String.slice(0, 100));
    return `data:image/${imageType};base64,${base64String}`;
  } catch (error) {
    throw new Error(`file ${filename} no exist ❌`)
  }
}

export {
  convertImageToBase64URL,
};

// test cases
const ok = convertImageToBase64URL("./public/test.png");
const err = convertImageToBase64URL();

  1. TypeScript version
import fs from 'node:fs';

type Filename = string;
type ImageType = 'png' | 'jpg' | 'jpeg' | 'gif' | 'webp';
type Base64String = `data:image/${ImageType};base64,${string}`;

const convertImageToBase64URL = (filename: Filename, imageType: ImageType = 'png'): Base64String => {
  try {
    const buffer = fs.readFileSync(filename);
    const base64String = Buffer.from(buffer).toString('base64');
    // console.log(`base64String`, base64String.slice(0, 100));
    return `data:image/${imageType};base64,${base64String}`;
  } catch (error) {
    throw new Error(`file ${filename} no exist ❌`)
  }
}

export {
  convertImageToBase64URL,
};

// test cases
const ok = convertImageToBase64URL("./public/test.png");
const err = convertImageToBase64URL();
/* 

Expected 1-2 arguments, but got 0.ts(2554)
An argument for 'filename' was not provided.
const convertImageToBase64URL: (filename: Filename, imageType?: ImageType) => Base64String

*/


refs

https://nodejs.org/api/buffer.html#static-method-bufferfrombuffer

-3
//instala via npm
npm install --save image-to-uri

//declara no codigo
const imageToUri = require('image-to-uri');

//implementa 
let imagem = imageToUri("caminho da sua imagem");
-14

Here`s another simple way, use it when listing your images

@{
    if (item.ImageData != null)
    {
        string imageBase64 = Convert.ToBase64String(item.ImageData);
        string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
        <img src="@imageSrc" width="100" height="100" />
    }
}
4
  • 18
    I don't think this is javascript at all Sep 21, 2017 at 14:44
  • 1
    Razor syntax after all Feb 15, 2018 at 13:28
  • excuse me, this question is about JS, not C# or ASP.NET. Jul 19, 2019 at 17:39
  • This looks like C#, The question is asking for Javascript
    – Awah Teh
    Sep 2, 2020 at 0:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.