图像保存和使用C#在SQL Server中检索asp.net [英] Image Save and Retrieve in SQL Server in asp.net using c#
本文介绍了图像保存和使用C#在SQL Server中检索asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将图像保存在SQL Server数据库中。
我将图像转换为在SQL Server的字节和商店,但现在我想保存的字节转换为图像,并使用C#显示它在asp.net中的标签上。
我尝试了很多,但没有找到一个解决方案。
下面是code(字节转换为图片)
如果(fImage.HasFile)
{
如果(fImage.PostedFile.ContentType ==图像/ JPG|| fImage.PostedFile.ContentType ==图像/ JPEG|| fImage.PostedFile.ContentType ==图像/ PNG)
{
INT filelenght = fImage.PostedFile.ContentLength;
字节[] = imagebytes新的字节[filelenght]
fImage.PostedFile.InputStream.Read(imagebytes,0,filelenght);
CMD的SqlCommand =新的SqlCommand();
cmd.CommandText =INSERT INTO tbImage(图)值(@img);
cmd.Connection = CON;
cmd.Parameters.AddWithValue(@ IMG,imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
的Response.Write(图像保存到数据库);
}
}
解决方案
这样的事会转换字节[]
到图片
:
的MemoryStream毫秒=新的MemoryStream(字节);
图像I = Image.FromStream(毫秒);
I am trying to save images in a SQL Server database.
I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.
I tried a lot but didn't find a solution.
Here is the code (convert bytes to Image)
if (fImage.HasFile)
{
if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
{
int filelenght = fImage.PostedFile.ContentLength;
byte[] imagebytes = new byte[filelenght];
fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into tbImage(Img) values(@img)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@img", imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Image saved to database");
}
}
解决方案
Something like this will convert Byte[]
to Image
:
MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
这篇关于图像保存和使用C#在SQL Server中检索asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文