How to Add an Image File into JSON Object

How do you put an image file in a json object?

I can think of doing it in two ways:

1.

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.

2.

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:

  • base64 encoding makes file sizes roughly 33% larger than their original binary representations, which means more data down the wire (this might be exceptionally painful on mobile networks)
  • data URIs aren’t supported on IE6 or IE7.
  • base64 encoded data may possibly take longer to process than binary data.

Source

Converting Image to DATA URI

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

  • lacks in browser support
  • has better compression
  • works for other file types as well.

Usage

convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});

Source

How can I add an image file into json object?

You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

You should also have a look at the following posts :

  • ByteArray in JSON
  • Binary Data in JSON String. Something better than Base64
  • BSON library for java

Hope this helps.

add picture to json?

In json objects you can provide the file path like that
"photo_large" :"file:///XXXXXXXXXXXXXXXXXXXX/XXXX/XXX/filename"
You can convert file path to URI and use it. Hope this help you.

How do i include an image file in json?

When you send a file to flask using multipart/form-data, the file will be at request.files, so, in your case, it would be

image_json = request.files['here is the key you add to the file on postman']

The other stuffs, called form-data, will be at request.form. So, to get that:

form_data = request.form

So, using postman, when you select multipartm/form-data, you will first give a name for the file, and then you will select it. The name (or key) will be the key used in the dict to get the file, as explained above.
Also, for the form part, the key will work the same way

Upload photo and send it as a json object

Well, first of all, in this block of code

string json = "{ user : { 'FirstName':'" + user_data.user.FirstName +
"','LastName': '" + user_data.user.LastName + "','Email': '" + user_data.user.Email +
"','Password': '" + user_data.user.Password + "','Country': '" + user_data.user.Country +
"','PhoneNumber': '" + user_data.ProfilePicture +
"'},'ProfilePicture': '" + user_data.PhoneNumber + "'}";

It looks like the keys PhoneNumber and ProfilePicture are swapped. You are setting the PhoneNumber to be the ProfilePicture and the ProfilePicture to be the PhoneNumber. It should be the other way around.

Also, I'm not sure what data type user_data.ProfilePicture is, but if it's an image, you can't just stuff it into JSON. JSON does not support binary data like an image. One option is to base64 encode the image data before putting it into JSON. Here's an example of doing this:

byte[] imageBytes = ...
var imageBytesStr = Convert.ToBase64String(imageBytes);

Then when you are constructing your JSON, set the ProfilePicture key to the base64 encoded string imageBytesStr. Your clients then must base64 decode the ProfilePicture string to get the image bytes. Then the clients must construct an image from these bytes.

Sent JSON object with image

You can always convert it to BASE64. Then it's a simple string which you can simply pass it within the JSON (or a different one).

EDIT

This is what i do in my case any time a user upload a file. Isimply transform the file chosen to a BASE64 string. There are some really nice resources out there about this.

onFileChanged(event) {
const file = event.target.files[0];
if (file.type.split('/')[0] !== 'image') {
this.validFile = false;
}
this.imageUploadModel.ImageType = file.type.split('/')[1];

const myReader: FileReader = new FileReader();
myReader.onloadend = (e) => {
this.imageUploadModel.Base64String = myReader.result.toString();
};
myReader.readAsDataURL(file);
}

This is my model

export class ImageUploadModel {
Title: string;
Description: string;
ImageType: string;
Base64String: string;
}

And i stringify it so i can send it on the body of the request:

 const body = JSON.stringify(this.imageUploadModel);


Related Topics



Leave a reply



Submit