Click here to Skip to main content
15,905,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I tried this piece of code below to convert byte[] into System.Drawing.Image.
Tuple<int, int, int> t1 = DecimalToDegrees(Convert.ToDecimal(lat));
Tuple<int, int, int> t2 = DecimalToDegrees(Convert.ToDecimal(lon));
string ss = Math.Abs(t1.Item1) + "%C2%B0" + t1.Item2 + "'" + t1.Item3 + "%22N+"
   + Math.Abs(t2.Item1) + "%C2%B0" + t2.Item2 + "'" + t2.Item3 + "%22W/@";
string s1 = ss + t1 + "," + lt2 + ",14z/data=!4m5!3m4!1s0x0:0x0!8m2!3d" + t1 + "!4d" + t2;
s1 = "https://www.google.com/maps/place/" + s1;
System.Net.WebClient client = new System.Net.WebClient();
byte[] data = client.DownloadData(s1);
// where  t1 and t2 are Lat and Lon values in decimal degrees;
System.Drawing.Image chartImage = Base64ToImage(data);  // Call the function below
....
  public System.Drawing.Image Base64ToImage(byte[] imageBytes)  {
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
    ms.Write(imageBytes, 0, imageBytes.Length);
    return System.Drawing.Image.FromStream(ms, true);
  }

However, I got an exception "Parameter is not valid" at
System.Drawing.Image.FromStream(ms, true);
What's wrong in my code? Thanks if you can point out.

What I have tried:

Failed in converting byte[] into an image
Posted
Updated 23-Jan-19 5:41am

1 solution

If the data is in Base64 format, then you need to convert it to raw byte data before you can load it into the stream and pass it to FromStream.
 
Share this answer
 
Comments
s yu 23-Jan-19 11:57am    
The data downloaded likes that below
byte[] data = client.DownloadData(s1);
I am not sure its format is Base64. Could you provide your advisory on that issue? Thanks.
OriginalGriff 23-Jan-19 12:02pm    
I'm working from the name of your method:

public System.Drawing.Image Base64ToImage(byte[] imageBytes)

Does imply you think it's Base64 ...

Use the debugger to look at the data in imageBytes, and if it's Base64 it should be obvious. Copy it to an online Base64 decoder and see if it likes it.
s yu 23-Jan-19 13:12pm    
Whatever tried , always failed. The byte[] object is downloaded from a google map. I would guess there is some format issue. Thanks.
OriginalGriff 23-Jan-19 13:58pm    
I'd suggest you save the byte data as a file and see if it has an image signature inside it. It may be a try that .NET doesn't understand, but that doesn't mean there isn't an easy way to convert it if you are lucky!
s yu 24-Jan-19 11:40am    
The key how to convert the downloaded byte[] into an image, which always fails. Will test more. Thanks.

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