zoukankan      html  css  js  c++  java
  • .net二进制图片存储与读取的常见方法

    .NET二进制图片存储与读取的常见方法有以下几种:

    .NET二进制图片存储:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[].

    1.参数是图片路径:返回Byte[]类型: 

    1. publicbyte[] GetPictureData(string imagepath)
    2. {
    3. /**/////根据图片文件的路径使用文件流打开,并保存为byte[]
    4. FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
    5. byte[] byData = newbyte[fs.Length];
    6. fs.Read(byData, 0, byData.Length);
    7. fs.Close();
    8. return byData;
    9. }

    2.参数类型是Image对象,返回Byte[]类型: 

    1. publicbyte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
    2. {
    3. //将Image转换成流数据,并保存为byte[]
    4. MemoryStream mstream = new MemoryStream();
    5. imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
    6. byte[] byData = new Byte[mstream.Length];
    7. mstream.Position = 0;
    8. mstream.Read(byData, 0, byData.Length);
    9. mstream.Close();
    10. return byData;
    11. }

    好了,这样通过上面的方法就可以把图片转换成Byte[]对象,然后就把这个对象保存到数据库中去就实现了把图片的二进制格式保存到数据库中去了。下面我就谈谈如何把数据库中的图片读取出来,实际上这是一个相反的过程。

    .NET二进制图片读取:把相应的字段转换成Byte[]即:Byte[] bt=(Byte[])XXXX

    1.参数是Byte[]类型,返回值是Image对象: 

    1. public System.Drawing.Image ReturnPhoto(byte[] streamByte)
    2. {
    3. System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
    4. System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
    5. return img;
    6. }

    2.参数是Byte[] 类型,没有返回值,这是针对asp.net中把图片从输出到网页上(Response.BinaryWrite)

    1. publicvoid WritePhoto(byte[] streamByte)
    2. {
    3. // Response.ContentType 的默认值为默认值为“text/html”
    4. Response.ContentType = "image/GIF";
    5. //图片输出的类型有: image/GIF image/JPEG
    6. Response.BinaryWrite(streamByte);
    7. }

    补充:

    针对Response.ContentType的值,除了针对图片的类型外,还有其他的类型:

    1. Response.ContentType = "application/msword";
    2. Response.ContentType = "application/x-shockwave-flash";
    3. Response.ContentType = "application/vnd.ms-excel";

    另外可以针对不同的格式,用不同的输出类型以适合不同的类型:  

    1. switch (dataread("document_type"))
    2. {
    3. case"doc":
    4. Response.ContentType = "application/msword";
    5. case"swf":
    6. Response.ContentType = "application/x-shockwave-flash";
    7. case"xls":
    8. Response.ContentType = "application/vnd.ms-excel";
    9. case"gif":
    10. Response.ContentType = "image/gif";
    11. case"Jpg":
    12. Response.ContentType = "image/jpeg";
    13. }

    以上就介绍了.NET二进制图片存储和读取的常见方法。

  • 相关阅读:
    物联网市场碎片化严重 物联网网关设计挑战重重
    物联网市场碎片化严重 物联网网关设计挑战重重
    物联网市场碎片化严重 物联网网关设计挑战重重
    越做越大的行李寄存生意,老板竟是3个95后
    互联网人失业理由排行榜,每一个都戳破职场真相
    读小说赚钱吗?这个年入百万
    BI驾驶舱的必备知识
    2019开源BI软件排行榜
    主流的开源bi工具
    企业为什么需要BI决策系统?
  • 原文地址:https://www.cnblogs.com/baozi/p/3213769.html
Copyright © 2011-2022 走看看