Skip to content

Instantly share code, notes, and snippets.

@zhangzhhz
Created March 25, 2022 16:54
Show Gist options
  • Save zhangzhhz/a344c6c09860acd3b9cb901874f0e872 to your computer and use it in GitHub Desktop.
Save zhangzhhz/a344c6c09860acd3b9cb901874f0e872 to your computer and use it in GitHub Desktop.
Encoding an image using base64 and decoding it

NodeJS

// base64 encoding a file
const base64EncodedString = fs.readFileSync(imageFileName).toString('base64');
// saving a base64 encoded image to a file
fs.writeFileSync(imageFileName, Buffer.from(base64EncodedString, 'base64'))

Python

# base64 encoding a file
with open(imageFileName, 'rb') as image:
    base64_encoded_bytes = base64.b64encode(image.read())
    base64_encoded_string = base64_encoded_bytes.decode()
# saving a base64 encoded image to a file
image_64_decoded = base64.b64decode(base64_encoded_string)
with open(imageFileName, 'wb') as image:
    image.write(image_64_decoded)

Go

import (
    "encoding/base64"
    "io/ioutil"
)

// base64 encoding a file
binaryData, _ := ioutil.ReadFile(imageFileName)
base64EncodedString := base64.StdEncoding.EncodeToString(binaryData)
// saving a base64 encoded image to a file
based64DecodedBytes, _ := base64.StdEncoding.DecodeString(base64EncodedString)
ioutil.WriteFile(imageFileName, based64DecodedBytes, 0644)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment