问题
i have a application which crops an image and save it
the process was to load an image, crop it, delete the original image(so i can replace it) and, save it.
this is my code:
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); }
}
}
This is for locating the margins that will be used to crop the image.
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");
}
and this is for cropping and saving of image
The error shows at line System.IO.File.Delete(@cwd + "\\t" + (x + 1) + ".jpg"
it says
The process cannot access the file 'C:\Users....\t2.jpg' because it is being used by another process.
I'm trying to look where i have been wrong for days, and still nothing.
Please help me.
回答1:
Bitmap TempImage = new Bitmap(@cwd + "\\t" + (x + 1) + ".jpg", true);
pictureBox.Image = (Image)TempImage.Clone();
TempImage.Dispose();
The Clone() method doesn't do what you hope it does. It still keeps a lock on the file, the memory mapped file object is shared between the two image objects. Disposing the first one just closes one handle on the object, the pictureBox.Image object still has the other handle opened. Write it like this instead:
pictureBox.Image = new Bitmap(TempImage);
来源:https://stackoverflow.com/questions/9250752/ioexception-was-unhandled