from an image received in json string how to get the image back ?

Hello,

i receive images from a json result. this images are in a string.
i succeed to transform the json object received into  a C# object.

now the c# object has the string that represents the images.

how to get back to the image ?

thank you in advance.
Erwin PombettAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Karrtik IyerSoftware ArchitectCommented:
Given that you have converted image to bytes and then to string before sending as shown below, you can use the client code shown below to convert it back to image.

private string CreateBase64Image(byte[] fileBytes)
{
Image streamImage;
using (MemoryStream ms = new MemoryStream(fileBytes))
{
streamImage = ScaleImage(Image.FromStream(ms));
}
using (MemoryStream ms = new MemoryStream())
{
streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
}

And in client side,

$('#image1').attr('src', 'data:image/png;base64,' + imageString);
Erwin PombettAuthor Commented:
Hello karrtik,
thank you for your answer.

i dont understant what to do with your code.


this is the kind of object i have after deserializing with newtonsoft.json

public class picture
{
  public string name { get; set }
  public string image {get; set}
}


do i have to convert first my string (image) to bytes[] ?  and then use your function ?

could you be more verbose to explain please...i'm having hard time to figure out this.

thank you in advance.
Karrtik IyerSoftware ArchitectCommented:
Hi toshi, the first part is the sending side where image is converted to bytes and then string. On the receiving side, is the client side in my comment, where the string received is converted back to image. If you want, if you give me some time, I can build a sample and share it with you.
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

Erwin PombettAuthor Commented:
sure !

i'll be glad to receive a sample.

i have to send the images as a response to a webservice call.
my images can be jpg or png.


thanks
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."Commented:
You need to figure out how the sender encoded the image data. More than likely, it's in base-64 encoding as Karrtik Iyer mentions, but you should double-check with the sender of the data. However it is encoded, you need to de-encode that data into bytes. Then you can write those bytes to disk in order to view the file.

Also, Karrtik Iyer shows writing a PNG file, but you need to confirm what kind of image format the sender gave you. If you've got a JPEG, then it doesn't make sense to write it as a PNG file.
Karrtik IyerSoftware ArchitectCommented:
Hi Toshi, Here is sample below. I have attached the PNG that I used first to serialize and then the PNG that I recreated from JSON for your reference using the code below. I have used JSON.NET library from JSON.NET
Step 1>  A program below JSONWriter, to serialize Image to JSON, written to text file, please change file paths as per drives in your computer, also current format considered is PNG, you can do similar thing for any other image format that you want.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Drawing;

namespace JSonWriter
{
    
    public class Picture
    {
        public string Name { get; set; }
        public string Image {get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Image imgfile = Image.FromFile(@"G:\karrtik\source\EE\JSONTest\JSonWriter\Test.png");
            Picture pic = new Picture {Image = CreateBase64Image(imgfile), Name = "Test.png"};
            string json = JsonConvert.SerializeObject(pic);
            File.WriteAllText("MyPicAsJSon.txt",json);
        }
        private static string CreateBase64Image(Image rhsimage)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                rhsimage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

    }

}
PNG Input :
[embed=file 1071128]

Open in new window

2> Step 2: Another program, JSON Reader, to read file from disk, and converts JSON back to Image and recreate a PNG back from JSON.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Drawing;
using System.Drawing.Imaging;
using System.Security.Cryptography;

namespace JSONReader
{
    public class Picture
    {
        public string Name { get; set; }
        public string Image { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string jsonfromfile = File.ReadAllText(@"G:\karrtik\source\EE\JSONTest\JSONReader\MyPicAsJSon.txt");
            Picture m = JsonConvert.DeserializeObject<Picture>(jsonfromfile);
            Byte[] imgBytes = Convert.FromBase64String(m.Image);
            using (MemoryStream ms = new MemoryStream(imgBytes))
            {
                Image pngImage = Image.FromStream(ms);
                string cmpfilepath = @"G:\karrtik\source\EE\JSONTest\JSONReader\" + m.Name;
                pngImage.Save(cmpfilepath,ImageFormat.Png);
            }
        }
    }
}

Open in new window

PNG Output:
Test._AfterDeserialize.pngTest_BeforeSerilaize.png

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSON

From novice to tech pro — start learning today.