C#将图片与字节流相互转换并显示到页面上示例源码,图片转换成字节流先要转换的IMage对象,转换后返回字节流。字节流转换成图片,要转换的字节流,转换得到的Image对象,根据图片路径返回图片的字节流。
C#将图片和字节流相互转换代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Drawing; usingSystem.IO; namespaceMicrosoft.Form.Base { classImageToByte { /// <summary> /// 图片转换成字节流 /// </summary> /// <param name="img">要转换的Image对象</param> /// <returns>转换后返回的字节流</returns> publicstaticbyte[] ImgToByt(Image img) { MemoryStream ms = newMemoryStream(); byte [] imagedata = null ; img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); imagedata = ms.GetBuffer(); returnimagedata; } /// <summary> /// 字节流转换成图片 /// </summary> /// <param name="byt">要转换的字节流</param> /// <returns>转换得到的Image对象</returns> publicstaticImage BytToImg( byte [] byt) { MemoryStream ms = newMemoryStream(byt); Image img = Image.FromStream(ms); returnimg; } // /// <summary> /// 根据图片路径返回图片的字节流byte[] /// </summary> /// <param name="imagePath">图片路径</param> /// <returns>返回的字节流</returns> privatestaticbyte[] getImageByte(stringimagePath) { FileStream files = newFileStream(imagePath, FileMode.Open); byte [] imgByte = newbyte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); returnimgByte; } } } |
将字节流转换为图片文件显示到页面上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
//Byte[] result; System.IO.MemoryStream ms = new
MemoryStream(result, 0, result.Length) Response.ClearContent(); Response.ContentType = "image/Gif" ; Response.BinaryWrite(ms.ToArray()); 或者添加一个处理图片的Handler,内容如下: <%@ WebHandler Language= "C#"
Class= "Handler"
%> using
System.Web; using
System.IO; public
class
Handler : IHttpHandler { public
void
ProcessRequest (HttpContext context) { int
CategoryID = int .Parse(context.Request.QueryString[ "CategoryID" ]); //调用Categories.GetPicture取得图片stream Stream stream = CategoriesPicture.GetPicture(CategoryID); if
(stream != null ) { //取得图片stream大小 int
buffersize = ( int )stream.Length; //建立buffer System.Byte[] buffer = new
System.Byte[buffersize ] ; //调用stream.Read,从stream读取到buffer,并返回count int
count = stream.Read(buffer, 0, buffersize); //返回图片字段buffer if
(count!=0) context.Response.OutputStream.Write(buffer, 0, count); } } public
bool
IsReusable { get
{ return
false ; } } } |