I want to convert image(Texture2D) data to Base64 string and store in JSON format as of now am getting image texture, it’s a kind of screenshot from live rendering camera. And I want the same image data into JSON format, Please suggest me with any example.
This is how am converting texture to Base64 then JSON.
There’s nothing in JSON that’s designed to store images or raw bytes and I would be genuinely surprised if it worked. Why are you trying to store it in JSON, and not, say, a PNG file?
Json is the javascript object notation. So it describes a structure of a selected set of primitive types (strings, numbers, boolean and null) and structure elements (objects and arrays). You create your base64 string and just pass it to the “ToJson” method which makes no sense. It’s just a single string. There is no structure at all. While a single string value is technically a valid json value, Unity’s JsonUtility only supports an object as root object.
You named your variable TextureArray but it’s not an array, just a single string. It’s completely unclear what the endresult should looks like. Judging by your variable name you may want to store multiple textures inside the file? However it’s not clear how and when you want to “add more” textures. You can not somehow just “add” another element to an actual array in a json encoded object hierarchy. To add something to a json representation of an object hierarchy you have to first read the old json, convert it into objects, arrays and values, apply the changes you want and then re-encode it as json and overwrite the whole file with the new content.
Though as I said it’s not clear what you want to do here.
Furthermore the rest of your code is even more confusing. ExternalCall has been deprecated long a go. Also it was just for interacting with browser javascript in a web build. So if we assume this is actually a web build, the last part of your code won’t work at all. While it’s possible to use the System.IO.File even in WebGL, you can not access any files on any actual drives. You use dataPath which in a webgl build would point to the URL where your application is hosted. You can not “write” to an URL. Unity provides the persistent data path to a virtual file system that is mapped to the LocalStorage of the browser.
In short the code as well as your question here is a complete mess.
I have created Multiple image capture app where I can capture image from live rendering camera and save it to my local assets folder it’s working well and am getting Texture2D but now I need to convert image data to Base64 string and store in JSON file. Every time when I capture/delete image, it should update JSON file, and next time when you start the app, it should read the JSON file first and if any image data is found, should show it in the scroll view which I have already created.
Nothing in that comment suggests that JSON is the correct place to store this data. You’re asking “how do I put the square peg in the round hole”, but there’s a square hole right next to it that you should be using.
It sounds like what you’d really be better off with is a directory of PNG files. You can write the files pertty straightforwardly using File.WriteAllBytes. For reading it out, you can read the directory contents with the DirectoryInfo class, iterate through them with its IterateFiles method, read the data in with File.ReadAllBytes, then convert those bytes to a Texture2D using Texture2D.LoadImage. JSON is not the tool for this.
For anyone still looking for the answer to this, the code below should work :):
using System;
using UnityEngine;
using UnityEngine.UI;
public class TestImageString : MonoBehaviour
{
public Texture2D texture;
public Image imageToPutTex;
// Start is called before the first frame update
void Start()
{
string json = ConvertTextureToJson(texture);
Sprite outputSprite = ConvertTextureJsonToSprite(json);
Debug.Log(json);
imageToPutTex.sprite = outputSprite;
}
//Convert a texture to a string and then store it in Json
private string ConvertTextureToJson(Texture2D tex)
{
string TextureArray = Convert.ToBase64String(tex.EncodeToPNG());
string jsonOutput = JsonUtility.ToJson(new StoreJson(TextureArray));
return jsonOutput;
}
//Convert a json string to Sprite
private Sprite ConvertTextureJsonToSprite(string json)
{
StoreJson test = JsonUtility.FromJson<StoreJson>(json);
byte[] b64_bytes = Convert.FromBase64String(test.imageFile);
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(b64_bytes);
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), Vector2.zero);
return sprite;
}
}
/// <summary>
/// Store your Image as a string in this class
/// </summary>
[Serializable]
public class StoreJson
{
public string imageFile;
public StoreJson(string imageFile)
{
this.imageFile = imageFile;
}
}
Before using that code, anyone coming across this thread should read the previous replies in this thread. Even if storing texture data in a JSON is technically possible, it is still a Very Bad Idea ™. Loading this is going to be much slower and error-prone because literally no image-creation algorithms are optimized for creating and loading images this way. It will be very easy to corrupt this data on accident (where image-loading from files often has error correction). If you do need to access a corrupted image for whatever reason, there are programs that can reconstruct parts of a corrupted image file, and there are zero recovery options for if you’ve used this weird PNG-data-in-a-json monstrosity.
And while it’s not impossible to imagine a situation where it would actually be useful to do this, such a situation would be vanishingly rare. If you’re just saving image data to a folder like OP was, just save the images to the folder.
Yes, it’s adviced to not use this method unless absolutely necessary. In my case I needed to import and export data containers(a data container class) from my application during runtime so storing it into a json worked best for my case as my application was an offline one. Alternatively, you can store your images anywhere on cloud and store the address to the image in a string than texture data as a string.