PictureControl
namespace AuthenticationTestClient
{
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
/// <summary>
/// PictureControl的摘要描述。
/// </summary>
public class PictureControl
{
public PictureControl(){}
[FlagsAttribute]
public enum ImgStyle {JPG, BMP, GIF};
private byte[] _ImgArray = new byte[1];
private Image _Image;
public byte[] ImgArray
{
get
{
if (_ImgArray == null){ return null;}
return _ImgArray;
}
}
public Image Image
{
get
{
if (_Image == null) return null;
return _Image;
}
}
/// <summary>
///装载图片
/// </summary>
/// <param name="FilterStyle"></param>
/// <returns></returns>
public static PictureControl LoadImage (ImgStyle FilterStyle)
{
PictureControl PC = new PictureControl ();
OpenFileDialog FileDialog = new OpenFileDialog ();
FileDialog.Filter = PC.CombinFilter (FilterStyle);
if (FileDialog.ShowDialog() == DialogResult.OK)
{
PC._Image = Image.FromFile (FileDialog.FileName);
FileStream fStream = new FileStream (FileDialog.FileName,
FileMode .Open, FileAccess.Read, FileShare.Read);
PC._ImgArray = new byte[fStream.Length];
fStream.Read (PC._ImgArray, 0, (int)fStream.Length);
fStream.Flush ();
fStream.Close ();
}
else
{
return null;
}
FileDialog.Dispose ();
return PC;
}
public static PictureControl ShowImage (byte[] ImgArray)
{
MemoryStream mStream = new MemoryStream ();
mStream.Write (ImgArray, 0, ImgArray.Length );
PictureControl PC = new PictureControl ();
PC._Image = Image.FromStream (mStream);
return PC ;
}
/// <summary>
///合并enum
/// </summary>
/// <param name="FilterStyle"></param>
/// <returns></returns>
private string CombinFilter (ImgStyle FilterStyle)
{
string FilterString = "";
ImgStyle[] StyleArray = (ImgStyle[])Enum.GetValues (FilterStyle.GetType());
for (int i = 0; i < StyleArray.Length; i++)
{
if (FilterString == "")
FilterString = FilterStr(StyleArray[i]);
else
{
FilterString = FilterString + '|' + FilterStr (StyleArray[i]);
}
}
return FilterString;
}
/// <summary>
///取得实际的筛选值
/// </summary>
/// <param name="FilterStyle"></param>
/// <returns></returns>
private string FilterStr (ImgStyle FilterStyle)
{
string FilterString = "";
switch (FilterStyle)
{
case ImgStyle.BMP:
FilterString = "BMP (*.bmp)|*.bmp";
break;
case ImgStyle.JPG:
FilterString = "JPG (*.jpg)|*.jpg";
break;
case ImgStyle.GIF:
FilterString = "GIF (*.gif)|*.gif";
break;
default:
break;
}
return FilterString ;
}
}
}
//源码都有详细注释﹐很容易的。调用方法如下﹕
//this.pictureBox1.Image=PictureControl.ShowImage((PictureControl.LoadImage(PictureControl.ImgStyle.JPG)).ImgArray).Image;
// this.pictureBox1.Image = PictureControl.LoadImage(PictureControl.ImgStyle.JPG).Image;