Rejith
Rejith

Reputation: 15

Error when converting byte array to System.Drawing.Image

I'm using C# 4.5 Framework and MySql

MySqlDataReader reader = Command.ExecuteReader();

if (reader.Read())
{

   byte[] ReturnImage = reader["Photo"] as byte[];

   MemoryStream ms = new MemoryStream(ReturnImage);

   Image Photo = Image.FromStream(ms);  //Error is in this statement!! 
}

When this stmt is executed the following error displays "Parameter is not valid"

I couldn't find the answer from the web.. Somebody Pls help..

Upvotes: 1

Views: 139

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062745

The most likely cause here is that the contents of the longblob are not the raw image bytes. Rather than go around in circles, the first thing to do is to: compare them. For example, you say (comments) that the data came from a jpg file, via OpenFileDialog. In that case, compare them. Check that you have successfully stored and retrieved the image.

Let's suppose that the file in question is c:\Some\Photo.jpg - stored etc per whatever process. In that case, you should be able to check the contents are the same. Until the following reports success, all bets are off:

byte[] original = File.ReadAllBytes(@"c:\Some\Photo.jpg");
byte[] ReturnImage = reader["Photo"] as byte[];

if(Convert.ToBase64String(original) == Convert.ToBase64String(ReturnImage)) {
    Console.WriteLine("Success; the contents match");
} else {
    Console.WriteLine("Failure; the contents are different");
}

If this reports "Failure; the contents are different", then the error is most likely in one of:

  • the code where you prepare the image to be stored (populating parameters etc)
  • the stored procedure that does the storage
  • the code that fetches the image back from the database

If this reports "Success; the contents match": then and only then is it meaningful to look at the code that attempts to load the Image. In this scenario, and assuming that c:\Some\Photo.jpg loads in most other image loading tools ("paint", etc) - then it is possible that Image doesn't recognise the subformat. But my guess is that it is going to say "Failure; the contents are different".

Note that Convert.ToBase64String here is used solely as a lazy way to check binary equivalence. You wouldn't use it like this in production code, but it is fine for this purpose.

Upvotes: 1

Related Questions