利用 DataGridView 绘制图片列表(从Access读取图片)

本博客介绍了一种基于.NET平台的图像访问与管理方法,通过使用Access数据库存储图像元数据,并提供一系列功能如添加、复制、删除、预览、保存、旋转、绘制和查看图像。

摘要生成于 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 Text primary key, Bytes Image)", 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);
                    }
                    Application.ExitThread();
                }
            }
            #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.DoubleBuffered = true; // 双缓冲绘图。
            this.IsMdiContainer = true; // MDI 窗体。
            this.BackgroundImageLayout = ImageLayout.Zoom; // 图像按其原有的大小比例缩放。
            this.DesktopBounds = Screen.GetWorkingArea(this);
            openFile.Filter = "图像格式(*.BMP;*.GIF;*.JPG;*.PNG)|*.bmp;*.gif;*.jpg;*.png";
            openFile.Multiselect = true; // 允许选择多个文件。
            table = new DataTable("Images");
            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(this.BackgroundImage);
        }
        #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;
            BackgroundImage.Save(this.Text, BackgroundImage.RawFormat);
            Process.Start("mspaint.exe", this.Text);
        }
        #endregion

        #region RotateImage
        private void toolButtonLeft_Click(object sender, EventArgs e)
        {
            if (this.BackgroundImage == null)
                return;
            BackgroundImage.RotateFlip(RotateFlipType.Rotate90FlipXY); // 逆时针旋转图片90°。
            this.Refresh(); // 刷新图片。
        }

        private void toolButtonRight_Click(object sender, EventArgs e)
        {
            if (this.BackgroundImage == null)
                return;
            BackgroundImage.RotateFlip(RotateFlipType.Rotate90FlipNone); // 顺时针旋转图片90°。
            this.Refresh(); // 刷新图片。
        }
        #endregion

        #region SaveImage
        private void toolButtonSave_Click(object sender, EventArgs e)
        {
            Environment.CurrentDirectory = Application.StartupPath;
            BackgroundImage.Save(this.Text, BackgroundImage.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.Width = 148;
            gridView.BorderStyle = BorderStyle.Fixed3D;
            gridView.BackgroundColor = SystemColors.Window;
            gridView.Dock = DockStyle.Left;
            gridView.AutoGenerateColumns = false; // 禁用自动创建列。
            gridView.AllowUserToAddRows = false; // 隐藏添加行。
            gridView.AllowUserToResizeColumns = false; // 禁用调整列的大小。
            gridView.AllowUserToResizeRows = 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.KeyDown += new KeyEventHandler(gridView_KeyDown);
            gridView.DataSource = table.DefaultView;
        }

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

        private void gridViewImage_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewCell cell = gridView.CurrentCell;
            if (cell != null)
            {
                this.Text = cell.ToolTipText;
                this.BackgroundImage = cell.FormattedValue as Image;
                statusLabelImage.Text = string.Format("ImageSize = {0}", BackgroundImage.Size);
            }
            toolButtonDelete.Enabled = (cell != null);
            bool flag = (BackgroundImage != null);
            toolButtonCopy.Enabled = flag;
            toolButtonSave.Enabled = flag;
            toolButtonPaint.Enabled = flag;
        }

        private void gridView_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.Left:
                    --(BindingContext[table.DefaultView] as CurrencyManager).Position;
                    break;
                case Keys.Right:
                    ++(BindingContext[table.DefaultView] as CurrencyManager).Position;
                    break;
                case Keys.Enter:
                    this.DesktopBounds = Screen.GetWorkingArea(this);
                    this.BackgroundImageLayout = ImageLayout.Stretch;
                    e.SuppressKeyPress = true;
                    break;
                case Keys.Escape:
                    this.DesktopBounds = Screen.GetWorkingArea(this);
                    this.BackgroundImageLayout = ImageLayout.Zoom;
                    e.SuppressKeyPress = true;
                    break;
            }
        }
        #endregion
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值