将图像/图片格式保存在数据库中 [英] save image/picture format in Database
本文介绍了将图像/图片格式保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要保存图像,但出现错误.如何解决此错误?
Hi,
I need to save image but i got error.How to solved this error?
byte[] pic = new byte[1];
pic[0] = 0;
if (pcbPhoto.Image != null)
{
stream = new MemoryStream();
pcbPhoto.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);// error occur here...
pic = stream.ToArray();
}
错误:GDI +中发生一般错误.
问候,
Karthikeyan,
Bangalore.
error : A generic error occurred in GDI+.
Regards,
Karthikeyan,
Bangalore.
推荐答案
通常,发生此错误是因为尝试保存时使用了输出流,但是由于输出的是MemoryStream而不是这种情况.
抱歉,问题不在您显示的代码中-往后很多...
问题可能在于,您最初用于创建图像的流不再可用-在您进入Save方法时,该流已被关闭或处置.那是行不通的!
试试这个:
首先加载图像时,创建一个新图像作为实际图片的副本,并使用该副本-您可以处置读入的原始版本.例如:
Normally, this error occurs because the output stream is in use when you try to save, but since you are outputting to a MemoryStream that is not the case.
Sorry, but the problem is not in teh code you show - it''s a lot further back...
The problem is probably that the stream you used to create the image in the first place is no longer available - it has been closed or disposed by the time you get to the Save method. And that doesn''t work!
Try this:
When you load the image in the first place, create a new image as a copy of the actual picture, and use that - you can dispose of the original version you read in. For example:
Image myImage;
using (Image inputImage = Image.FromFile(@"D:\Temp\MyPic.jpg"))
{
myImage = new Bitmap(inputImage);
}
由于新图像未与文件或流关联,因此可以毫无问题地将其保存.
Because the new image is not associated with a file or stream, it can be saved with no problem.
您好,
使用此代码将图片读取为Bytes数组
Hi,
Use this code to read picture as Bytes array
MemoryStream stream=new MemoryStream();
pictureBox1.Image.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic=stream.ToArray();
然后将pic插入数据库
then insert pic into the database
SqlConnection con = new SqlConnection
("Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=123456");
SqlCommand com = new SqlCommand("insert into Employees(LastName,FirstName,Photo) values('aaaa','bbb',@Photo)", con);
com.Parameters.AddWithValue("@Photo", pic);
希望这对您有帮助,
A.Mandour
Hope this helps you,
A.Mandour
这篇关于将图像/图片格式保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文