Click here to Skip to main content
15,905,874 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a byte[] with image information stored. When I convert the byte[] to image it works but if I try convert byte[] to string and again string to byte[] and use that converted byte[] in ImageConverter it won't work

What I have tried:


This code doesn't work

byte[] buffer = ms.ToArray();
string bytes2string = Encoding.ASCII.GetString(buffer);
byte[] imageByte = Encoding.ASCII.GetBytes(bytes2string);
ImageConverter convertData = new ImageConverter();
Image image = (Image)convertData.ConvertFrom(imageByte);
Updated 18-Dec-22 4:03am
CHill60 18-Dec-22 9:24am    
So use the code that works? What is your question?
Member 14623639 18-Dec-22 9:33am    
The code is my previous code that works but I using that same working byte[] to convert to string and again to byte[] won't work.

1 solution

Here's how I do it:
Convert Image to byte[] array:
MemoryStream ms = new MemoryStream();
Byte[] bytes = ms.ToArray();
Convert byte[] array to Image:
MemoryStream ms = new MemoryStream(bytes);
Image imageOut = Image.FromStream(ms);
Don't go via strings unless you absolutely have to - and then use Base64 instead of "regular" strings - strings are always Unicode, and some of the values in your image can be interpreted wrongly by regular strings, leading to a byte array that isn't identical to the original after conversion.


How can I achieve sending image file name and image both in the same byte[]?

The sensible way would be to create a container class which holds a string and a byte array properties.
Then use JSON to build an easily transferable string, and deserialize it at the end.
If you use Newtonsoft.Json, it's trivial:
            Image image = Bitmap.FromFile(@"D:\Test Data\MyPic.jpg");
            pictureBox1.Image = image;
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            ImageWithName iwm1 = new ImageWithName() { Name = "Hello.jpg", ImageData = ms.ToArray() };
            string jsonBody = JsonConvert.SerializeObject(iwm1);
            ImageWithName iwm2 = JsonConvert.DeserializeObject<ImageWithName>(jsonBody);
            ms = new MemoryStream(iwm2.ImageData);
            image = Bitmap.FromStream(ms);
            pictureBox2.Image = image;

Share this answer
Member 14623639 18-Dec-22 10:43am    
How can I achieve sending image file name and image both in the same byte[]?
OriginalGriff 18-Dec-22 11:16am    
Answer updated
Member 14623639 18-Dec-22 22:42pm    
Thanks for the answer. I will check this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900