如何在不锁定图像文件的情况下将图像加载到 C# 程序中。单击“正常加载”按钮时,程序将使用以下代码显示图像文件。
// Load the image normally.
private void btnLoadNormally_Click(object sender, EventArgs e)
{if (picSample.Image != null) picSample.Image.Dispose();picSample.Image = new Bitmap("essential_algs_75.jpg");
}
此代码只是创建一个新的Bitmap,并将要加载的文件的名称传递给其构造函数。(Visual Studio 在构建程序时将文件复制到程序的可执行目录中,因此请在那里查找该文件。)如果您随后尝试使用文件资源管理器重命名或删除该文件,您将会失败,因为该文件已被锁定。基本上,程序会将文件保持锁定状态,以防以后需要使用它来绘制位图。
当您单击“加载解锁”按钮时,程序将使用以下代码来显示图像文件。
// Load the bitmap without locking it.
private void btnLoadUnlocked_Click(object sender, EventArgs e)
{if (picSample.Image != null) picSample.Image.Dispose();picSample.Image = LoadBitmapUnlocked("essential_algs_75.jpg");
}
完整代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace howto_load_image_unlocked
{public partial class Form1 : Form{public Form1(){InitializeComponent();}// Load the image normally.private void btnLoadNormally_Click(object sender, EventArgs e){if (picSample.Image != null) picSample.Image.Dispose();picSample.Image = new Bitmap("essential_algs_75.jpg");}// Load the bitmap without locking it.private void btnLoadUnlocked_Click(object sender, EventArgs e){if (picSample.Image != null) picSample.Image.Dispose();picSample.Image = LoadBitmapUnlocked("essential_algs_75.jpg");}// Load a bitmap without locking it.private Bitmap LoadBitmapUnlocked(string file_name){using (Bitmap bm = new Bitmap(file_name)){return new Bitmap(bm);}}// Open the book's web page.private void picSample_Click(object sender, EventArgs e){System.Diagnostics.Process.Start("http://www.csharphelper.com/algorithms.html");}}
}