Reputation: 3
i have an problem with read an image of SQL the strucure the my table is the next
CREATE TABLE [dbo].[Nota] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Titulo] [varchar](50) NOT NULL,
[Imagen] [image] NOT NULL
)
an the fields than i have saved in the DB is the next
Id Titulo Imagen
1 Nombreimagen 0x53797374656D2E427974655B5D
and my code is the follow
try
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Nota WHERE ID = '1'", @"Data Source=Server;Initial Catalog=DB;Integrated Security=True;User ID=User;Password=Pasword*");
da.Fill(ds, "Imagen");
byte[] imageBuffer = (byte[])ds.Tables["Imagen"].Rows[0]["Imagen"];
System.IO.MemoryStream ms = new System.IO.MemoryStream(imageBuffer);
pictureBox2.Image = Image.FromStream(ms);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
and my error is the follow
[System.ArgumentException] = {"Parameter is not valid."}
in the next line
pictureBox2.Image = Image.FromStream(ms);
Upvotes: 0
Views: 888
Reputation: 42434
You get that error whenever GDI isn't able to make an image out of the bytes you feed it.
Let's look at what is in the image field:
0x53797374656D2E427974655B5D
If I put that through a HexString to Byte converter and then ASCII (it helps a bit if you know the table) decode the result, for example with this code:
Encoding.ASCII.GetString( StringToByteArray("53797374656D2E427974655B5D")).Dump();
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
The result is:
System.Byte[]
and that is not an image. It is the result of the ToString() method of the type that held your image when you tried to insert or update that row. You might want to make sure the SqlParameter for your image has its DbType
property set to DbType.Binary
when you try to save that image.
You can't fix the problem in the code you show here, fix the root cause, fix the content of the field Imagen
in the row.
Upvotes: 1
Reputation: 165
Try to use data type varbinary(max) instead of image data type, image data type is being deprecated.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql
Upvotes: 1