Friday, March 23, 2012

read image from Sql Server

Hello!

My real problem is that i want to read an image from an Sql Server DB, resize them and send them, all this through a Web Service. I decide to split my problem in four steps:

1 - read image from Database

2 - Resize that image

3 - Send her back to the DB

4 - Send the image throw a web service after he use a dataset to read the data from the DB.

i try to read the database with this function

Code Snippet

public System.Drawing.Image ReadImgFromDB(Int64 imageID)

{

System.Drawing.Image image = null;

using (SqlConnection conn = new SqlConnection())

{

string connString = WebConfigurationManager.ConnectionStrings

["StringCC"].ConnectionString;

conn.ConnectionString = connString;

SqlCommand myCommand = new SqlCommand(

"SELECT Pic FROM Images WHERE ID='"+ imageID +"'", conn);

conn.Open();

byte[] imageData = (byte[])myCommand.ExecuteScalar();

System.IO.MemoryStream memStream = new System.IO.MemoryStream(imageData);

image = System.Drawing.Image.FromStream(memStream);

}

return image;

}

i introduce a valid image ID and i get this message

" System.ArgumentException: Parameter is not valid.
at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
at System.Drawing.Image.FromStream(Stream stream)
at Service.ReadImgFromDB(Int64 chaveI) in e:\Web Projects\WSservice\App_Code\Service.cs:line 48"--

line 48: "image = System.Drawing.Image.FromStream(memStream);"

Thank you!

Seems like the image is corrupt, the code looks ok, though you should use parametrized queries: This will prevent SQL injection

Code Snippet

SqlCommand myCommand = new SqlCommand("SELECT Pic FROM Images WHERE ID= @.imageID", conn);

SqlParameter paramImage = new SqlParameter(@.imageID, SqlType.Varchar,20); // Depends on your parameter type

paramImage.Value = imageID;

myCommand.Parameters.Add(paramImage);

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||

thank you for your reply.

Yes i usually use parameters, but for now i'm just "playing" with code.

I didn't check the images, i just assume that they're ok. i'll check them.

Thanks!

sql

No comments:

Post a Comment