FormImageAccess.cs

本文介绍了一个使用Access数据库存储和管理图像的应用程序。该程序利用C#实现,支持图像的添加、复制、删除等功能,并能够通过拖放操作进行图像导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using Access = Microsoft.Office.Interop.Access;

namespace ImageAccess
{
    static class Program
    {
        #region DllImportAttribute
        [DllImport("user32.dll", EntryPoint = "ShowWindow")]
        static extern bool ShowWindow(IntPtr handle, int flags);

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        static extern bool SetForegroundWindow(IntPtr handle);
        #endregion

        [STAThread]
        static void Main()
        {
            #region Mutex
            bool isCreated; // 互斥体名称须唯一。
            using (Mutex newMutex = new Mutex(true, @"Local/ImageAccess", out isCreated))
            {
                if (isCreated)
                {
                    string dbPath = Path.Combine(Application.StartupPath, "Images.mdb");
                    if (File.Exists(dbPath))
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        using (RegistryKey subKey = Application.UserAppDataRegistry)
                        {
                            FormImageAccess frame = new FormImageAccess();
                            subKey.SetValue("Handle", frame.Handle);
                            Application.Run(frame);
                        }
                        newMutex.ReleaseMutex(); // 释放互斥体的所属权。
                    }
                    else
                    {
                        Access.Application newAccess = new Access.Application();
                        newAccess.NewCurrentDatabase(dbPath);
                        dao.Database db = newAccess.CurrentDb();
                        db.Execute("create table [Images] (Name string primary key, Bytes LongBinary)", Type.Missing);
                        db.NewPassword("", "jinzhexian");
                        db.Close();
                        newAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                        newAccess = null;
                        GC.Collect();
                        Application.ExitThread();
                    }
                }
                else
                {
                    string text = string.Format("“{0}”应用程序已经运行。", AppDomain.CurrentDomain.FriendlyName);
                    MessageBox.Show(text, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    using (RegistryKey subKey = Application.UserAppDataRegistry)
                    {
                        IntPtr handle = new IntPtr(Convert.ToInt32(subKey.GetValue("Handle")));
                        ShowWindow(handle, 1);
                        SetForegroundWindow(handle);
                    }
                }
            }
            #endregion
        }
    }
}

 

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; // 窗体背景透明化。
            pictureBoxIMG.BackColor = Color.Transparent; // 图像背景透明化。
            pictureBoxIMG.SizeMode = PictureBoxSizeMode.Zoom; // 图像大小按其原有的大小比例被增加或减小。
            openFileImage.Filter = "图像格式(*.BMP;*.GIF;*.JPG;*.PNG)|*.bmp;*.gif;*.jpg;*.png";
            openFileImage.Multiselect = true; // 允许选择多个文件。
            table = new DataTable();
            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 (openFileImage.ShowDialog(this) == DialogResult.OK)
                ImageToAccess(openFileImage.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(pictureBoxIMG.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(gridViewImage.CurrentCellAddress.Y);
                }
        }
        #endregion

        #region PaintImage
        private void toolButtonPaint_Click(object sender, EventArgs e)
        {
            using (Process psi = new Process())
            {
                psi.StartInfo.FileName = "mspaint.exe"; // 启动画图。
                psi.StartInfo.WorkingDirectory = Environment.SystemDirectory;
                psi.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                psi.Start();
            }
        }
        #endregion

        #region RotateImage
        private void toolButtonRotate_Click(object sender, EventArgs e)
        {
            RotateFlipType rft = sender.Equals(toolButtonLeft) ? RotateFlipType.Rotate90FlipXY : RotateFlipType.Rotate90FlipNone;
            pictureBoxIMG.Image.RotateFlip(rft); // 旋转和翻转图像。
            pictureBoxIMG.Refresh(); // 刷新图片。
        }
        #endregion

        #region SaveImage
        private void toolButtonSave_Click(object sender, EventArgs e)
        {
            using (Bitmap bmp = new Bitmap(pictureBoxIMG.Image))
            {
                bmp.Save(Path.Combine(Application.StartupPath, this.Text));
            }
            Process.Start(Application.StartupPath);
            System.Threading.Thread.Sleep(300);
            SendKeys.SendWait(this.Text);
        }
        #endregion

        #region DataGridViewStyle
        private void DataGridViewStyle()
        {
            DataGridViewImageColumn imgColumn = new DataGridViewImageColumn();
            imgColumn.DataPropertyName = "Bytes";
            imgColumn.ImageLayout = DataGridViewImageCellLayout.Zoom; // 将图形按比例放大,直到达到其所在单元格的宽度或高度。
            imgColumn.Width = 128; // 设置图片宽度。
            gridViewImage.Columns.Add(imgColumn);
            gridViewImage.RowTemplate.Height = 128; // 设置图片高度。
            gridViewImage.BorderStyle = BorderStyle.Fixed3D;
            gridViewImage.BackgroundColor = this.BackColor;
            gridViewImage.AutoGenerateColumns = false; // 禁用自动创建列。
            gridViewImage.AllowUserToAddRows = false; // 隐藏添加行。
            gridViewImage.AllowUserToDeleteRows = false; // 禁用删除行。
            gridViewImage.AllowUserToResizeRows = false; // 禁用调整行的大小。
            gridViewImage.AllowUserToResizeColumns = false; // 禁用调整列的大小。
            gridViewImage.ColumnHeadersVisible = false; // 隐藏列标题。
            gridViewImage.RowHeadersVisible = false; // 隐藏行标题。
            gridViewImage.ReadOnly = true; // 禁用编辑单元格。
            gridViewImage.MultiSelect = false; // 用户仅能选择一个单元格、行或列。
            gridViewImage.ShowCellToolTips = true; // 显示单元格工具提示。
            gridViewImage.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(gridViewImage_CellToolTipTextNeeded);
            gridViewImage.SelectionChanged += new EventHandler(gridViewImage_SelectionChanged);
            gridViewImage.DataSource = table.DefaultView;
        }

        private void gridViewImage_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewCell cell = gridViewImage.CurrentCell;
            if (cell != null)
            {
                this.Text = cell.ToolTipText;
                pictureBoxIMG.Image = cell.FormattedValue as Bitmap;
            }
            toolButtonDelete.Enabled = (cell != null);
            toolButtonSave.Enabled = toolButtonCopy.Enabled = (pictureBoxIMG.Image != null);
        }

        private void gridViewImage_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
        {
            e.ToolTipText = table.DefaultView[e.RowIndex][0] as string;
        }

        private void pictureBoxIMG_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
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值