Convert Image to Base64 and Vice-versa
NOTE : When converting base64 to Image , make sure to remove the staring "data:image/png;base64" from the string.
Python
import pybase64
from PIL import Image
import matplotlib.pyplot as plt
from PIL import Image
import io
import numpy as np
# Takes base64 string and returns the Image as numpy array
def decodeBase64ToImage(base64_string):
# decoding base54 to bytes
print("Converting base64 to bytes...")
decoded = pybase64.standard_b64decode(base64_string)
print("LENGTH : ",len(decoded))
print("TYPE1 : ",type(decoded))
# converting bytes to image
print("Converting bytes to image...")
stream = io.BytesIO(decoded)
img = Image.open(stream)
print("Converting image to numpy array...")
img = np.array(img)
print("TYPE2 : ",type(img))
return img
from io import BytesIO
# Takes numpy array and decode's the image as base64
def encodeImageToBase64(numpy_img):
"""
code referenced from :
https://jdhao.github.io/2020/03/17/base64_opencv_pil_image_conversion/
Instead of saving the PIL Image object img to the disk, we save it to
im_file which is a file-like object.
"""
# Rescaling between 0-255 and convert to integers
img = Image.fromarray(np.uint8(numpy_img*255))
im_file = BytesIO()
img.save(im_file, format="JPEG")
im_bytes = im_file.getvalue() # im_bytes: image in binary format.
im_base64 = pybase64.standard_b64encode(im_bytes)
# decode bytes to string
encoded = im_base64.decode('utf-8')
return encoded
Javascript
var fs = require("fs");
// Takes image path and returns as base64
function encodeImageToBase64(img_path){
base64_img = fs.readFileSync(img_path, 'base64');
return base64_img;
}
// Takes base64 string and saves the decoded image.
function decodeBase64Image(base64_string, filename = "stylized_image.jpg") {
if (base64_img != null) {
var ReadableData = require("stream").Readable;
const imageBufferData = Buffer.from(base64_string, "base64");
var streamObj = new ReadableData();
streamObj.push(imageBufferData);
streamObj.push(null);
streamObj.pipe(fs.createWriteStream(filename));
console.log("Image Saved as : ",filename)
}
}
const img_path = "C:/Users/dipesh/Desktop/NST/photos/liberty.jpg";
const base64_Img = encodeImageToBase64(img_path);
decodeBase64Image(base64_Img)
Encode Image in ReactJS
// pass the filepath
function getBase64(file_path) {
const reader = new FileReader();
reader.onload = (event) => {
return event.target.result;
};
reader.readAsDataURL(file_path);
}
NOTE : https://www.npmjs.com/package/react-file-base64 (Use to create Base64 Image Uploader)
Comments
Post a Comment