图片保存到数据库,如果是sqlserver就是Image类型,如果保存到Oracle就是blob类型,在c#中相对应的就是byte[]类型,同时只需要对读出的数据强制转换就行(byte[])object.
1. 将图片保存为byte数组
//参数是图片路径,返回Byte[]类型
public byte[] GetPictureData(string imagepath) { FileStream file = new FileStream(imagepath, FileMode.Open); byte[] by = new byte[file.Length]; file.Read(by, 0, by.Length); file.Close(); return by; }
//参数是Image,返回Byte[]类型
public byte[] GetPictureData(System.Drawing.Image imgPhoto) { //将Image转换成流数据,并保存为byte[] MemoryStream mstream=new MemoryStream(); imgPhoto.Save(mstream,System.Drawing.Imaging.ImageFormat.Bmp); byte[]byData=new Byte[mstream.Length]; mstream.Position=0; mstream.Read(byData,0,byData.Length); mstream.Close(); return byData; }
2. 将byte数组转换为图片
//参数是Byte[]类型,返回值是Image对象 public System.Drawing.Image ReturnPhoto(byte[] streamByte) { MemoryStream me = new MemoryStream(streamByte); return System.Drawing.Image.FromStream(ms); } //参数是Byte[]类型,没有返回值,这是针对asp.net中把图片从输出到网页上 public void WritePhoto(byte[] streamByte) { Response.ContentType="image/GIF"; Response.BinaryWrite(streamByte); }
3. byte[]和string的转换
//byte[] 转换为string byte[] by; string str=System.Convert.ToBase64String(by); //string转换为byte[] string str; byte[] by=System.Convert.FromBase64String(str);
时间: 2024-10-11 22:54:26