Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass images in a server's response using JSON? Base64?

In my android app, I show some users in a ListView. I want to display (user's pic, first_name, last_name). Right now, it works only with first_name and last_name. I want to add the picture. The data JSON I receive from my server (python) is like this:

[{"profil":"first_name": "Jim", "last_name": "Carrey"}}, "_id": {"$oid": "4d595cda1d41c81536000000"}}, {"profil":{"first_name": "Mathieu", "last_name": "Polnari"}}, "_id": {"$oid": "4d5916581d41c80e88000000"}}, {"profil": {"first_name": "Vincent", "last_name": "Fatou"}}, "_id": {"$oid": "4d58fc7e1d41c8090e000000"}}...] 

It should be better if I add one parameter in that JSON for the picture.

Do you think it is a good idea to return the picture as a string in the JSON et use Base64 to decode it?

like image 320
user420574 Avatar asked Feb 20 '11 15:02

user420574


People also ask

Can I send image with JSON?

Yes but it would be inefficient. The best you could do with JSON is encode all the raw image data using base 64. That would be making use of 6 bits per byte instead of 8. If you have a MongoDb, you could store the image as a document.

Can I send Base64 in JSON?

Save this answer. Show activity on this post. Base64 is a safe encoding for JSON.


2 Answers

Technically it's perfectly ok to encode binary data as base64 string and include it in JSON.

But, as @servermanfail noted, you might be better off with embedding links to images into JSON and downloading them in the second step.

The added benefit would be size/speed of transfer, as base64 stream is 4/3 the size of the original binary stream (33% overhead).

Also, in this case, you could cache images.

like image 122
Peter Knego Avatar answered Oct 18 '22 02:10

Peter Knego


I would suggest adding a JSON parameter which contains a URL to the resource.

For added security, you could create encrypted URLs by adding a md5 with salt checksum to the resource, like http://server.com/images/1234567890123456789012345678901234567890/image.jpg - this is the method facebook.com uses.

like image 27
servermanfail Avatar answered Oct 18 '22 00:10

servermanfail