C#byte数组与Image的相互转换实例代码
功能需求:
1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库读取的byte数组转换为Image对象,赋值给相应的控件显示。
3、从图片byte数组得到对应图片的格式,生成一张图片保存到磁盘上。
这里的Image是System.Drawing.Image。
1
2
3
|
//Get an image from file
Image image = Image.FromFile( "D:\\test.jpg" );
Bitmap bitmap = new Bitmap( "D:\\test.jpg" );
|
以下三个函数分别实现了上述三个需求:
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace NetUtilityLib
{
public static class ImageHelper
{
/// <summary>
/// Convert Image to Byte[]
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte [] ImageToBytes(Image image)
{
ImageFormat format = image.RawFormat;
using (MemoryStream ms = new MemoryStream())
{
if (format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}
else if (format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}
else if (format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}
else if (format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}
else if (format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}
byte [] buffer = new byte [ms.Length];
//Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
}
/// <summary>
/// Convert Byte[] to Image
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image BytesToImage( byte [] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
/// <summary>
/// Convert Byte[] to a picture and Store it in file
/// </summary>
/// <param name="fileName"></param>
/// <param name="buffer"></param>
/// <returns></returns>
public static string CreateImageFromBytes( string fileName, byte [] buffer)
{
string file = fileName;
Image image = BytesToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{
file += ".jpeg" ;
}
else if (format.Equals(ImageFormat.Png))
{
file += ".png" ;
}
else if (format.Equals(ImageFormat.Bmp))
{
file += ".bmp" ;
}
else if (format.Equals(ImageFormat.Gif))
{
file += ".gif" ;
}
else if (format.Equals(ImageFormat.Icon))
{
file += ".icon" ;
}
System.IO.FileInfo info = new System.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);
return file;
}
}
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/u013816709/article/details/50695713