IOException was unhandled
本文关键字:unhandled was IOException | 更新日期: 2023-09-27 18:24:07
我有一个应用程序,它可以裁剪并保存图像
这个过程是加载一个图像,裁剪它,删除原始图像(这样我就可以替换它),然后保存它。
这是我的代码:
private void DetectSize(object sender, EventArgs e)
{
int x = 1;
Bitmap TempImage = new Bitmap(@cwd + "''t" + (x + 1) + ".jpg", true);
pictureBox.Image = (Image)TempImage.Clone();
TempImage.Dispose();
Bitmap imgPart = new Bitmap(pictureBox.Image);
int imgHeight = imgPart.Height;
int imgWidth = imgPart.Width;
HalfWidth = imgWidth / 2;
MaxWidth = imgWidth;
try
{
Bitmap imgPart1 = new Bitmap(pictureBox.Image);
Color c;
for (int i = 0; i < imgPart1.Width; i++)
{
for (int j = 0; j < imgPart1.Height; j++)
{
c = imgPart1.GetPixel(i, j);
string cn = c.Name;
for (int z = 0; z <= 9; z++)
{
if (z < 10)
{
if (cn == "ff00000" + z)
{
if (i < HalfWidth)
{
MinWidth = i;
}
else
{
if (i < MaxWidth)
{
MaxWidth = i;
}
}
}
}
else
{
if (cn == "ff0000" + z)
{
if (i < HalfWidth)
{
MinWidth = i;
}
else
{
if (i < MaxWidth)
{
MaxWidth = i;
}
}
}
}
}
}
}
MinWidth += 1;
MaxWidth -= 1;
MaxWidth = imgWidth - MaxWidth;
imgPart1.Dispose();
imgPart.Dispose();
lblLeftMargin.Text = Convert.ToString(MinWidth);
lblRightMargin.Text = Convert.ToString(MaxWidth);
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
}
这是为了定位将用于裁剪图像的边距。
private void CropSave(object sender, EventArgs e)
{
int x = 1;
Bitmap croppedBitmap = new Bitmap(pictureBox.Image);
croppedBitmap = croppedBitmap.Clone(
new Rectangle(
MinWidth, 0,
(int)croppedBitmap.Width - MinWidth - MaxWidth,
1323),
System.Drawing.Imaging.PixelFormat.DontCare);
if (System.IO.File.Exists(@cwd + "''t" + (x + 1) + ".jpg"))
System.IO.File.Delete(@cwd + "''t" + (x + 1) + ".jpg");
croppedBitmap.Save(@cwd + "''t" + (x + 1) + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
croppedBitmap.Dispose();
MessageBox.Show("File " + (x + 1) + "Done Cropping");
}
这是为了裁剪和保存图像
错误显示在System.IO.File.Delete(@cwd + "''t" + (x + 1) + ".jpg"
行
上面写着
进程无法访问文件"C:''Users…"。。。。''t2.jpg’,因为它正被另一个进程使用。
几天来,我一直在努力寻找我错在哪里,但仍然一无所获
请帮帮我。
Bitmap TempImage = new Bitmap(@cwd + "''t" + (x + 1) + ".jpg", true);
pictureBox.Image = (Image)TempImage.Clone();
TempImage.Dispose();
Clone()方法并没有达到您希望的效果。它仍然对文件保持锁定,内存映射的文件对象在两个图像对象之间共享。处理第一个只会关闭对象pictureBox的一个句柄。Image对象的另一个句柄仍处于打开状态。改为这样写:
pictureBox.Image = new Bitmap(TempImage);