I am making a database for video games, each containing elements like name, genre, and and image of the game. Is it possible to put images into a json object for the db? If not is there a way around this?
I can think of doing it in two ways:
Storing the file in file system in any directory (say dir1
) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg
), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png
)and insert it in the JSON.
Base 64 Encoding, It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:
Source
A.) Canvas
Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.
function convertToDataURLviaCanvas(url, callback, outputFormat){ var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function(){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var dataURL; canvas.height = this.height; canvas.width = this.width; ctx.drawImage(this, 0, 0); dataURL = canvas.toDataURL(outputFormat); callback(dataURL); canvas = null; }; img.src = url; }
Usage
convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL });
Supported input formats image/png
, image/jpeg
, image/jpg
, image/gif
, image/bmp
, image/tiff
, image/x-icon
, image/svg+xml
, image/webp
, image/xxx
B.) FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.
function convertFileToBase64viaFileReader(url, callback){ var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function () { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.send(); }
This approach
Usage
convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL });
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With