While Reading byte[] from json file show a difference in size

somaraj k 21 Reputation points
2022-01-20T18:22:13.093+00:00

Hi ,

I am storing a byte[] ( image pixel data) in a json file .
The byte array is encoded to UTF-8 before storing to json using System.Text.Encoding.UTF8.GetString(imagePixelDataByteArray)
When I read back the Image pixel data from json ,I find that the size of the data I got is more that the actual size of the data present in the json file
(ie) the line marked 1 and 2 in below code .

why is this happening ? what is the correct way to store byte[] in json and read it back with out corrupting it .

        string file = @"E:/UserData/z004df4s/Documents/corrupted/NM_11364753_100006_CalibrationTrendData_20210816T122659-0500.json";  
        //deserialize JSON from file    
        string json = System.IO.File.ReadAllText(file);  

        var data = (JObject)JsonConvert.DeserializeObject(json);              
        var ImageString = data["ImageData"].Value<string>();  

       Console.WriteLine(ImageString.Length);  -----------------------------1  

        var binaryImage = System.Text.Encoding.UTF8.GetBytes(ImageString);   

       Console.WriteLine(binaryImage.Length); ---------------------------------2  

Thanks in advance
Somaraj

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,175 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,031 Reputation points
    2022-01-20T18:48:19.8+00:00

    Images files are binary while JSON is text. The standard approach is encoding the binary data into a Base64 string (text). This allows the image to be serialized to a text stream. Keep in mind, Base64 increases the file size by about 1/3.

    0 comments No comments

0 additional answers

Sort by: Most helpful