How to save a base64-encoded image to disk ?

How to save a base64-encoded image to disk ?

Asked on October 24, 2018 in node.js.
Add Comment


  • 4 Answer(s)

    Once we create the buffer with the proper encoding, we just need to write the buffer to the file.

    var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
     
    require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
    console.log(err);
    });
    

    new Buffer(…, ‘base64’) converts the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string and you can just write that byte array to the file.

    Answered on October 24, 2018.
    Add Comment

    This code will be helpful for any base64 image format and save it in the proper format in the database:

        // Save base64 image to disk
        try
        {
            // Decoding base-64 image
            // Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
            function decodeBase64Image(dataString)
            {
                var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
                var response = {};
     
            if (matches.length !== 3)
            {
                return new Error('Invalid input string');
            }
     
            response.type = matches[1];
            response.data = new Buffer(matches[2], 'base64');
     
            return response;
        }
     
        // Regular expression for image type:
        // This regular image extracts the "jpeg" from "image/jpeg"
        var imageTypeRegularExpression = /\/(.*?)$/;
     
        // Generate random string
        var crypto = require('crypto');
        var seed = crypto.randomBytes(20);
        var uniqueSHA1String = crypto
                                 .createHash('sha1')
                                 .update(seed)
                                 .digest('hex');
     
        var base64Data =     data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';
     
        var imageBuffer = decodeBase64Image(base64Data);
        var userUploadedFeedMessagesLocation = '../img/upload/feed/';
     
        var uniqueRandomImageName = 'image-' + uniqueSHA1String;
        // This variable is actually an array which has 5 values,
        // The [1] value is the real image extension
        var imageTypeDetected = imageBuffer
                                           .type
                                        .match(imageTypeRegularExpression);
     
        var userUploadedImagePath = userUploadedFeedMessagesLocation +
                                                   uniqueRandomImageName +
                                                    '.' +
                                                    imageTypeDetected[1];
     
        // Save decoded binary image to disk
        try
        {
        require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
                                     function()
                                    {
                                     console.log('DEBUG - feed:message: Saved to disk image attached by user:',      userUploadedImagePath);
                                     });
        }
        catch(error)
        {
        console.log('ERROR:', error);
        }
     
    }
    catch(error)
    {
        console.log('ERROR:', error);
    }
    
    Answered on October 24, 2018.
    Add Comment

    This code will Convert file with base64 string to png image.

    In this four variants are used.

    var {promisify} = require('util');
    var fs = require("fs");
    var readFile = promisify(fs.readFile)
    var writeFile = promisify(fs.writeFile)
    async function run () {
     
        // variant 1
        var d = await readFile('./1.txt', 'utf8')
        await writeFile("./1.png", d, 'base64')
     
        // variant 2
        var d = await readFile('./2.txt', 'utf8')
        var dd = new Buffer(d, 'base64')
        await writeFile("./2.png", dd)
     
        // variant 3
        var d = await readFile('./3.txt')
        await writeFile("./3.png", d.toString('utf8'), 'base64')
     
        // variant 4
        var d = await readFile('./4.txt')
        var dd = new Buffer(d.toString('utf8'), 'base64')
        await writeFile("./4.png", dd)
    }
    run();
    
    Answered on October 24, 2018.
    Add Comment

    Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

    var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
    
    require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
      console.log(err);
    });

    new Buffer(…, ‘base64’) will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

    Update

    As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

    Answered on February 21, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.