using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace WinFormImage
{
public partial class FormImage : Form
{
private OpenFileDialog openFile;
private PictureBox picture;
public FormImage()
{
InitializeComponent();
openFile = new OpenFileDialog();
openFile.Filter = "ImageFormat (*.BMP;*.GIF;*.JPG;*.PNG)|*.bmp;*.gif;*.jpg;*.png";
openFile.Multiselect = false;
picture = new PictureBox();
picture.Dock = DockStyle.Fill;
picture.SizeMode = PictureBoxSizeMode.Zoom;
this.Controls.Add(picture);
this.AllowDrop = true;
this.HelpButton = true;
this.MaximizeBox = this.MinimizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
}
#region OnDragEnter
protected override void OnDragEnter(DragEventArgs e)
{
base.OnDragEnter(e);
this.Activate(); // 激活窗体并给予它焦点。
DataObject data = e.Data as DataObject;
if (data.ContainsFileDropList())
{
string filePath = data.GetFileDropList()[0];
if (Regex.IsMatch(Path.GetExtension(filePath), @".(bmp|gif|jpg|png)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。
{
picture.Image = Image.FromFile(filePath);
//picture.ImageLocation = filePath;
//using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath)))
//{
// picture.Image = Image.FromStream(ms);
//}
//using (Stream ms = new System.Data.SqlTypes.SqlBytes(File.ReadAllBytes(filePath)).Stream)
//{
// picture.Image = Image.FromStream(ms);
//}
}
}
}
#endregion
#region OnHelpButtonClicked
protected override void OnHelpButtonClicked(System.ComponentModel.CancelEventArgs e)
{
base.OnHelpButtonClicked(e);
e.Cancel = true;
if (openFile.ShowDialog(this) == DialogResult.OK)
{
picture.Image = Image.FromFile(openFile.FileName);
//picture.ImageLocation = openFile.FileName;
//using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(openFile.FileName)))
//{
// picture.Image = Image.FromStream(ms);
//}
//using (Stream ms = new System.Data.SqlTypes.SqlBytes(File.ReadAllBytes(openFile.FileName)).Stream)
//{
// picture.Image = Image.FromStream(ms);
//}
}
}
#endregion
}
}
WebForm Image:
Response.ContentType = FileUpload.PostedFile.ContentType;
Response.BinaryWrite(FileUpload.FileBytes);
using (Stream os = Response.OutputStream)
{
os.Write(FileUpload.FileBytes, 0, FileUpload.PostedFile.ContentLength);
os.Flush();
}
Clipboard Image:
if (openFile.ShowDialog(this) == DialogResult.OK)
{
IDataObject data = Clipboard.GetDataObject();
using (Bitmap bmp = new Bitmap(openFile.FileName))
{
Clipboard.SetImage(bmp);
if (Clipboard.ContainsImage())
picture.Image = Clipboard.GetImage();
}
Clipboard.SetDataObject(data, true);
}