views:

172

answers:

3

I have a stored procedure that return a varbinary(max) type data. I want to convert that data into an Image.

But I have problems with this line:

public Image CargarAvatar(string login)
        {
            System.Object[] Args = new System.Object[1];
            Args[0] = login;

            DataTable X = new DataTable();
            X = TraerDataTable("sp_CargarAvatarUsuario", Args);

            byte[] ImagemByte = Convert.to (X.Rows[0][0].ToString());


            MemoryStream ms = new MemoryStream();
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

Please help! :D

A: 

I'm not sure about converting an Int to a byte[] in this case, as I don't see an int anywhere. It's certainly possible to do, I just don't see an application in this case.

You had two real problems. One was creating the byte[], which obviously you know as it wouldn't compile. The second was getting those bytes into the stream.

public Image CargarAvatar(string login)
{
    System.Object[] Args = new System.Object[1];
    Args[0] = login;

    DataTable X = TraerDataTable("sp_CargarAvatarUsuario", Args); // No need to create a new DataTable and overwrite it with the return value of TraerDataTable. One assignment will do.

    byte[] ImagemByte = (byte[])X.Rows[0][0]; // If this is an Image in the database, then this is already a byte[] here and just needs to be casted like so.             

    MemoryStream ms = new MemoryStream(ImagemByte); // You need to pass the existing byte[] into the constructor of the stream so that it goes against the correct data
    Image returnImage = Image.FromStream(ms);

    return returnImage;
}
Adam Robinson
+4  A: 

A varbinary field is returned as a byte array, so you only need to cast it:

byte[] ImagemByte = (byte[])X.Rows[0][0];

Then you use the array to create the memory stream:

MemoryStream ms = new MemoryStream(ImagemByte);
Guffa
A: 

You're trying to create the image from an empty memory stream. Pass the byte array as a parameter to the MemoryStream constructor :

MemoryStream ms = new MemoryStream(ImagemByte);
Thomas Levesque