int count = 0;
private void pictureBoxImageToCrop_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || crop == false) return;
if (DrawingRects.Count > 0 && pictureBoxImageToCrop.Image != null && selectedPath != "")
{
if ((x >= 0 && x <= pictureBoxImageToCrop.Image.Size.Width) && (y >= 0 && y <= pictureBoxImageToCrop.Image.Size.Height))
{
var dr = DrawingRects.Last();
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
rectImage = cropAtRect((Bitmap)pictureBoxImageToCrop.Image, dr.Rect);
if (saveRectangles)
{
count++;
rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented
);
using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
{
sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter++;
}
else
{
var stream = ToMemoryStream(rectImage);
var image = System.Drawing.Image.FromStream(stream);
pictureBoxCroppedImages.Image = image;
}
// Here I added an additional check to make sure the Image is set in pictureBoxCroppedImages
if (saveRectangles && pictureBoxCroppedImages.Image == null)
{
pictureBoxCroppedImages.Image = rectImage;
}
pixelsCounter = rect.Width * rect.Height;
pictureBoxCroppedImages.Invalidate();
var newKey = $"{dr.Location}, {dr.Size}";
var newItem = new MyListBoxItem
{
Message = newKey + "," + FileList[newKey],
ItemColor = Color.Green
};
MyItems.Add(newItem);
listBoxCroppedImages.SelectedIndex = MyItems.Count - 1;
pictureBoxImageToCrop.Focus();
// Check if the image is null before using it
if (pictureBoxCroppedImages.Image != null)
{
Graphics g = Graphics.FromImage(this.pictureBoxCroppedImages.Image);
g.Clear(this.pictureBoxCroppedImages.BackColor);
}
}
}
else
{
if (clearRectangles)
{
DrawingRects.Clear();
pictureBoxImageToCrop.Invalidate();
}
x = 0;
y = 0;
}
}
}