using System;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace ImageAccess
{
public partial class FormImageAccess : Form
{
#region 自定义对象
private OleDbConnection ole;
private DataTable table;
private ChineseLunisolarCalendar lunarCalendar = new ChineseLunisolarCalendar();
#endregion
public FormImageAccess()
{
#region
InitializeComponent();
this.AllowDrop = true; // 启用拖放操作。
this.TransparencyKey = this.BackColor; // 窗体背景透明化。
picture.BackColor = Color.Transparent; // 图像背景透明化。
picture.SizeMode = PictureBoxSizeMode.Zoom; // 图像大小按其原有的大小比例被增加或减小。
picture.MouseClick += new MouseEventHandler(picture_MouseClick);
openFile.Filter = "图像格式(*.BMP;*.GIF;*.JPG;*.PNG)|*.bmp;*.gif;*.jpg;*.png";
openFile.Multiselect = true; // 允许选择多个文件。
table = new DataTable("Image");
table.Locale = CultureInfo.InvariantCulture; // 固定区域性。
DataColumn column = table.Columns.Add("Name", typeof(String));
table.Columns.Add("Bytes", typeof(Byte[]));
table.Constraints.Add("PK", column, true); // 创建主键。
table.DefaultView.ApplyDefaultSort = true; // 使用默认排序。
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.Jet.OLEDB.4.0"; // "Microsoft.ACE.OLEDB.12.0";
builder.DataSource = @"|DataDirectory|Images.mdb"; // @"|DataDirectory|Images.accdb";
builder["Jet OLEDB:Database Password"] = "jinzhexian";
ole = new OleDbConnection(builder.ConnectionString);
using (OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [Images]", ole))
{
table.BeginLoadData(); // 在加载数据时关闭通知、索引维护和约束。
adapter.Fill(table);
table.EndLoadData(); // 在加载数据后打开通知、索引维护和约束。
}
DataGridViewStyle();
#endregion
}
#region ChineseLunisolarCalendar
private void timerDate_Tick(object sender, EventArgs e)
{
Application.CurrentCulture.ClearCachedData();
DateTime solar = DateTime.Now;
int month = lunarCalendar.GetMonth(solar);
int leapMonth = lunarCalendar.GetLeapMonth(lunarCalendar.GetYear(solar));
if (0 < leapMonth && leapMonth <= month)
--month;
statusLabelTime.Text = string.Format("{0:F} [{1} {2:00}]", solar, DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1], lunarCalendar.GetDayOfMonth(solar));
}
#endregion
#region AddImage
private void toolButtonAdd_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog(this) == DialogResult.OK)
ImageToAccess(openFile.FileNames);
}
protected override void OnDragEnter(DragEventArgs e)
{
base.OnDragEnter(e);
this.Activate();
DataObject data = e.Data as DataObject;
if (data.ContainsFileDropList())
ImageToAccess(data.GetData(DataFormats.FileDrop) as string[]);
}
private void ImageToAccess(string[] fileList)
{
foreach (string filePath in fileList)
{
if (!Regex.IsMatch(Path.GetExtension(filePath), @".(bmp|gif|jpg|png)", RegexOptions.IgnoreCase))
continue;
string imgName = Path.GetFileName(filePath);
int index = table.DefaultView.Find(imgName);
if (index > -1)
{
MessageBox.Show(this, string.Format("图像“{0}”已存在!", imgName), "确认图片添加", MessageBoxButtons.OK, MessageBoxIcon.Warning);
(BindingContext[table.DefaultView] as CurrencyManager).Position = index;
continue;
}
Byte[] bytes = File.ReadAllBytes(filePath);
table.Rows.Add(imgName, bytes);
using (OleDbCommand cmd = new OleDbCommand("insert into [Images] values(?,?)", ole))
{
cmd.Parameters.Add("@Name", OleDbType.VarWChar, imgName.Length, "Name").Value = imgName;
cmd.Parameters.Add("@Bytes", OleDbType.LongVarBinary, bytes.Length, "Bytes").Value = bytes;
ole.Open();
cmd.ExecuteNonQuery();
ole.Close();
}
}
}
#endregion
#region CopyImage
private void toolButtonCopy_Click(object sender, EventArgs e)
{
Clipboard.SetImage(picture.Image);
}
#endregion
#region DeleteImage
private void toolButtonDelete_Click(object sender, EventArgs e)
{
if (MessageBox.Show(this, string.Format("确实要删除“{0}”吗?", this.Text), "确认图片删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
using (OleDbCommand cmd = new OleDbCommand("delete from [Images] where Name=?", ole))
{
cmd.Parameters.Add("@Name", OleDbType.VarWChar, Text.Length, "Name").Value = this.Text;
ole.Open();
cmd.ExecuteNonQuery();
ole.Close();
table.DefaultView.Delete(gridView.CurrentCellAddress.Y);
toolButtonDelete.Enabled = (gridView.CurrentCellAddress.Y > -1);
}
}
#endregion
#region PaintImage
private void toolButtonPaint_Click(object sender, EventArgs e)
{
Environment.CurrentDirectory = Application.StartupPath;
Image img = picture.Image;
img.Save(this.Text, img.RawFormat);
Process.Start("mspaint.exe", this.Text);
}
#endregion
#region RotateImage
private void toolButtonLeft_Click(object sender, EventArgs e)
{
if (picture.Image == null)
return;
picture.Image.RotateFlip(RotateFlipType.Rotate90FlipXY); // 逆时针旋转图片90°。
picture.Refresh(); // 刷新图片。
}
private void toolButtonRight_Click(object sender, EventArgs e)
{
if (picture.Image == null)
return;
picture.Image.RotateFlip(RotateFlipType.Rotate90FlipNone); // 顺时针旋转图片90°。
picture.Refresh(); // 刷新图片。
}
#endregion
#region SaveImage
private void toolButtonSave_Click(object sender, EventArgs e)
{
Environment.CurrentDirectory = Application.StartupPath;
Image img = picture.Image;
img.Save(this.Text, img.RawFormat);
Process.Start(this.Text);
}
#endregion
#region DataGridViewStyle
private void DataGridViewStyle()
{
DataGridViewImageColumn imgColumn = new DataGridViewImageColumn();
imgColumn.DataPropertyName = "Bytes";
imgColumn.ImageLayout = DataGridViewImageCellLayout.Zoom; // 将图形按比例放大,直到达到其所在单元格的宽度或高度。
imgColumn.Width = 128; // 设置图片宽度。
gridView.Columns.Add(imgColumn);
gridView.RowTemplate.Height = 128; // 设置图片高度。
gridView.BorderStyle = BorderStyle.Fixed3D;
gridView.BackgroundColor = SystemColors.Window;
gridView.AutoGenerateColumns = false; // 禁用自动创建列。
gridView.AllowUserToAddRows = false; // 隐藏添加行。
gridView.AllowUserToResizeRows = false; // 禁用调整行的大小。
gridView.AllowUserToResizeColumns = false; // 禁用调整列的大小。
gridView.ColumnHeadersVisible = false; // 隐藏列标题。
gridView.RowHeadersVisible = false; // 隐藏行标题。
gridView.MultiSelect = false; // 用户仅能选择一个单元格、行或列。
gridView.ShowCellToolTips = true; // 显示单元格工具提示。
gridView.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(gridViewImage_CellToolTipTextNeeded);
gridView.SelectionChanged += new EventHandler(gridViewImage_SelectionChanged);
gridView.DataSource = table.DefaultView;
}
private void gridViewImage_SelectionChanged(object sender, EventArgs e)
{
DataGridViewCell cell = gridView.CurrentCell;
if (cell != null)
{
this.Text = cell.ToolTipText;
picture.Image = cell.FormattedValue as Image;
statusLabelImage.Text = string.Format("ImageSize = {0}", picture.Image.Size);
}
toolButtonDelete.Enabled = (cell != null);
bool flag = (picture.Image != null);
toolButtonCopy.Enabled = flag;
toolButtonSave.Enabled = flag;
toolButtonPaint.Enabled = flag;
}
private void gridViewImage_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = table.DefaultView[e.RowIndex][0] as string;
}
private void picture_MouseClick(object sender, MouseEventArgs e)
{
CurrencyManager manager = BindingContext[table.DefaultView] as CurrencyManager;
switch (e.Button)
{
case MouseButtons.Left:
--manager.Position;
break;
case MouseButtons.Right:
++manager.Position;
break;
}
}
#endregion
}
}