Centroid tracking issue on Aforge C# - c#

I am creating a program that can track multiple objects and get their centroid eventually I would use these centroids to connect to the nearest centroid of another object. But my problem is, my program tracks only one significant object on the video and it doesn't seem to display the centroid of this object. anyone can help me?
namespace Video_Processing_fixed_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap video;
Graphics g;
bool OnOff;
int mode;
int thoigiandemnguoc = 5;
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame+=new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
video = (Bitmap)eventArgs.Frame.Clone();
Bitmap video2 = (Bitmap)eventArgs.Frame.Clone();
g = Graphics.FromImage(video2);
g.DrawString("Test", new Font("Arial", 20), new SolidBrush(Color.White), new PointF(2, 2));
g.Dispose();
if (mode == 1)
{
// create filter
EuclideanColorFiltering filter = new EuclideanColorFiltering();
// set center colol and radius
filter.CenterColor = Color.FromArgb(215, 30, 30);
filter.Radius = 100;
// apply the filter
filter.ApplyInPlace(video2);
BlobCounter blobcounter = new BlobCounter();
blobcounter.MinWidth = 5;
blobcounter.MinHeight = 5;
blobcounter.FilterBlobs = true;
blobcounter.ObjectsOrder = ObjectsOrder.Area;
blobcounter.ProcessImage(video2);
Blob[] blobs = blobcounter.GetObjectsInformation();
AForge.Point Center = new AForge.Point();
if (blobs.Length > 0)
{
Center.X = blobs.Average(c => c.CenterOfGravity.X);
Center.Y = blobs.Average(c => c.CenterOfGravity.Y);
}
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach(Rectangle recs in rects)
if (rects.Length > 0)
{
foreach (Rectangle objectRect in rects)
{
Graphics graphic = Graphics.FromImage(video2);
using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
{
graphic.DrawRectangle(pen, objectRect);
}
graphic.Dispose();
}
}
( Pen pen = new Pen(Color.White,3))
pictureBox2.Image = video2;
pictureBox1.Image = video;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning==true)
{
FinalFrame.SignalToStop();
FinalFrame.WaitForStop();
}
}
private void button2_Click(object sender, EventArgs e)
{
pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
}
private void ButObjTrack_Click(object sender, EventArgs e)
{
mode = 1;
}
private void StopButt_Click(object sender, EventArgs e)
{
FinalFrame.SignalToStop();
}
}
}

You do not display the average center value. Change these lines:
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach(Rectangle recs in rects)
if (rects.Length > 0)
{
foreach (Rectangle objectRect in rects)
{
Graphics graphic = Graphics.FromImage(video2);
using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
{
graphic.DrawRectangle(pen, objectRect);
}
graphic.Dispose();
}
}
To these:
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Graphics graphic = Graphics.FromImage(video2);
foreach (Rectangle objectRect in rects)
{
graphic.DrawRectangle(Pens.LightGreen, objectRect);
}
graphic.DrawRectangle(Pens.Red, Center.X - 4, Center.Y - 4, 8, 8);
graphic.Dispose();
}
}

Related

Resize rectangle with form Size in real time?

Here is the following rectangle below:
When I resize the form, I need this rectangle to match the size of the form.
When changing the width of the rectangle, do not interfere with its visibility within the form.
I'm using the following:
Note:
I did the rectangle manually, but if you have rectangle ready, better yet!
public Form1()
{
InitializeComponent();
this.Paint += Form1_Paint;
this.rectangles = new Dictionary<string, Rectangle>();
this.sizeScreen = this.Size;
this.sizeRectangles = new Size(8, 8);
this.brush = new SolidBrush(Color.Red);
FillLeft();
FillRight();
FillUp();
FillDown();
}
private Size sizeScreen;
private Size sizeRectangles;
private SolidBrush brush;
private Dictionary<string, Rectangle> rectangles;
private void FillLeft()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("left", rectangle);
}
private void FillRight()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = this.sizeScreen.Width - (this.sizeRectangles.Width * 5),
Y = this.sizeRectangles.Height
};
this.rectangles.Add("right", rectangle);
}
private void FillUp()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("up", rectangle);
}
private void FillDown()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeScreen.Height - (this.sizeRectangles.Height * 11)
};
this.rectangles.Add("down", rectangle);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < this.rectangles.Count; i++)
{
e.Graphics.FillRectangles(this.brush, this.rectangles.Values.ToArray());
}
}
I want to set the rectangle on the form when it is resized
This is the way I'm creating the rectangle, but it does not stay right on the screen, to resize it I do not know
I think this would simplify what you are trying to do:
const int PenWidth = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
You could even add a margin:
const int PenWidth = 10;
const int PenMargin = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
r.Inflate(-PenMargin, -PenMargin);
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
To prevent traces (suggested by Wyck):
private void Form1_Resize(object sender, EventArgs e)
{
Invalidate();
}
Handle the Resize event and call Invalidate in the handler. Create a Pen of the desired color and width and set its Alignment to Inset. Handle the Paint event and in the handler call DrawRectangle passing in the ClientRectangle of the form.
Here is an example.
const float borderWidth = 8.0f;
Pen borderPen = new Pen(Color.Red, borderWidth) { Alignment = System.Drawing.Drawing2D.PenAlignment.Inset };
public Form2()
{
InitializeComponent();
this.Paint += Form2_Paint;
this.Resize += Form2_Resize;
}
private void Form2_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(borderPen, this.ClientRectangle);
}
Apply the following fixes to the code:
Set ResizeRedraw property of the form to true. It sets the underlying style for the form so by each resize it sends the paint message and you don't need to handle Resize event.
Use DrawRectangle and draw using wide pen. So you don't need to fill multiple rectangles.
Set the PenAlignment to Inset. So you don't need to calculate the location of rectangle.
Do dispose the pen when you don't need it.
Example
public Form1()
{
InitializeComponent();
ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var pen = new Pen(Color.Red, PenWidth))
{
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
e.Graphics.DrawRectangle(pen, ClientRectangle);
}
}
i have used this on my current project. when ever you resize the form, it will automatically resize all the object inside your form
i have class named clsResize and i call this on the form load.
1st you have to initialize the class inside the form then create 2 new method.
see example below
public partial class frmNewForm : Form
{
clsResize _form_resize;
public string selectedProd;
public frmNewForm()
{
InitializeComponent();
_form_resize = new clsResize(this);
this.Load += _Load;
this.Resize += _Resize;
}
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
private void _Resize(object sender, EventArgs e)
{
_form_resize._resize();
}
}
and here is the class that i used.
public class clsResize
{
List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
private bool showRowHeader = false;
public clsResize(Form _form_)
{
form = _form_; //the calling form
_formSize = _form_.ClientSize; //Save initial form size
_fontsize = _form_.Font.Size; //Font size
}
private float _fontsize { get; set; }
private System.Drawing.SizeF _formSize {get;set; }
private Form form { get; set; }
public void _get_initial_size() //get initial size//
{
var _controls = _get_all_controls(form);//call the enumerator
foreach (Control control in _controls) //Loop through the controls
{
_arr_control_storage.Add(control.Bounds); //saves control bounds/dimension
//If you have datagridview
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
}
}
public void _resize() //Set the resize
{
double _form_ratio_width = (double)form.ClientSize.Width /(double)_formSize.Width; //ratio could be greater or less than 1
double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height; // this one too
var _controls = _get_all_controls(form); //reenumerate the control collection
int _pos = -1;//do not change this value unless you know what you are doing
try
{
foreach (Control control in _controls)
{
// do some math calc
_pos += 1;//increment by 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height)); //use for sizing
System.Drawing.Point _controlposition = new System.Drawing.Point((int)
(_arr_control_storage[_pos].X * _form_ratio_width), (int)(_arr_control_storage[_pos].Y * _form_ratio_height));//use for location
//set bounds
control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize); //Put together
//Assuming you have a datagridview inside a form()
//if you want to show the row header, replace the false statement of
//showRowHeader on top/public declaration to true;
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
//Font AutoSize
control.Font = new System.Drawing.Font(form.Font.FontFamily,
(float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return;
}
}
private void _dgv_Column_Adjust(DataGridView dgv, bool _showRowHeader) //if you have Datagridview
//and want to resize the column base on its dimension.
{
int intRowHeader = 0;
const int Hscrollbarwidth = 5;
if (_showRowHeader)
intRowHeader = dgv.RowHeadersWidth;
else
dgv.RowHeadersVisible = false;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Dock == DockStyle.Fill) //in case the datagridview is docked
dgv.Columns[i].Width = ((dgv.Width - intRowHeader) / dgv.ColumnCount);
else
dgv.Columns[i].Width = ((dgv.Width - intRowHeader - Hscrollbarwidth) / dgv.ColumnCount);
}
}
private static IEnumerable<Control> _get_all_controls(Control c)
{
return c.Controls.Cast<Control>().SelectMany(item =>
_get_all_controls(item)).Concat(c.Controls.Cast<Control>()).Where(control =>
control.Name != string.Empty);
}
}

Print Image in Picturebox and the Highlighted Areas

I'm using WinForms. In my form i have a picturebox that contains an image. I provided my code which highlights images by right-clicking and dragging the mouse.
How do I print the image and what i highlighted in the picturebox?
private Random _rnd = new Random();
private Point _pt;
private Point _pt2;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
//set the upper left point of our selection rectangle
if (e.Button == MouseButtons.Left)
_pt = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//display the selected part when mouse button gets released
if (e.Button == MouseButtons.Left)
{
GenerateBmp();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
//if we have a valid rectangle, draw it
if (_pt.X - _pt2.X != 0 && _pt.Y - _pt2.Y != 0)
{
//fill
using (SolidBrush sb = new SolidBrush(Color.FromArgb(95, 255, 255, 0)))
e.Graphics.FillRectangle(sb, new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y));
//draw
e.Graphics.DrawRectangle(Pens.Blue, new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y));
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//set the bottom right one
if (e.Button == MouseButtons.Left)
{
_pt2 = e.Location;
this.pictureBox1.Invalidate();
}
}
private void GenerateBmp()
{
//check, if we have a valid rectangle
if (_pt2.X - _pt.X > 0 && _pt2.Y - _pt.Y > 0)
{
//create that rectangle
Rectangle r = new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y);
//create a new Bitmap with the size of the selection-rectangle
Bitmap bmp = new Bitmap(r.Width, r.Height);
//draw the selectex part of the original image
using (Graphics g = Graphics.FromImage(bmp))
g.DrawImage(this.pictureBox1.Image, new Rectangle(0, 0, r.Width, r.Height), r, GraphicsUnit.Pixel);
}
}
private Bitmap SetUpPictures(PictureBox pb)
{
//create a bitmap to display
Bitmap bmp1 = new Bitmap(pb.ClientSize.Width, pb.ClientSize.Height);
//get the graphics-context
using (Graphics g = Graphics.FromImage(bmp1))
{
//get a random, opaque, color
Color c = Color.FromArgb(255, _rnd.Next(256), _rnd.Next(256), _rnd.Next(256));
g.Clear(c);
//better smoothinmode for round shapes
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//draw ten shapes to the bitmap
for (int i = 0; i < 10; i++)
{
//loaction and size rectangle
Rectangle r = new Rectangle(_rnd.Next(pb.ClientSize.Width / 2), _rnd.Next(pb.ClientSize.Height / 2),
_rnd.Next(pb.ClientSize.Width / 2), _rnd.Next(pb.ClientSize.Height / 2));
//random color
Color c2 = Color.FromArgb(_rnd.Next(256), _rnd.Next(256), _rnd.Next(256), _rnd.Next(256));
//one color brush
using (SolidBrush sb = new SolidBrush(c2))
{
//check, if i is odd or even and decide on that to draw rectangles or ellipses
if ((i & 0x01) == 1)
g.FillEllipse(sb, r);
else
g.FillRectangle(sb, r);
}
}
}
//return our artwork
return bmp1;
}
private void Btn_Print_Click(object sender, EventArgs e)
{
System.Drawing.Printing.PrintDocument myPrintDocument1 = new System.Drawing.Printing.PrintDocument();
PrintDialog myPrinDialog1 = new PrintDialog();
myPrintDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(DVPrintDocument_PrintPage);
myPrinDialog1.Document = myPrintDocument1;
if (myPrinDialog1.ShowDialog() == DialogResult.OK)
{
myPrintDocument1.Print();
}
}
private void DVPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(pictureBox1.Image, 25, 25, 800, 1050);
var rc = new RectangleF(0, 0, pictureBox1.Image.Width / 100f, pictureBox1.Image.Height / 100f);
e.Graphics.DrawImage(pictureBox1.Image, rc);
}
You can draw the content of picturebox simply using DrawToBitmap method:
For example:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(10, 10, 100, 100));
}
private void button1_Click(object sender, EventArgs e)
{
this.printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
var bmp=new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
this.pictureBox1.DrawToBitmap(bmp,this.pictureBox1.ClientRectangle);
e.Graphics.DrawImageUnscaled(bmp, 0, 0);
}
And here is the printed result:

Why when i create the bitmap it's empty all white?

private Bitmap CropImage()
{
Bitmap pic = pictureBoxSnap.Image as Bitmap;
Bitmap cropped = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(cropped))
{
g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
rect, GraphicsUnit.Pixel);
}
pic.Save(#"c:\temp\testingitimage.jpg");
cropped.Save(#"c:\temp\testingitimage1.bmp");
return cropped;
}
I added this two lines of Save to test what i get. The first one pic i see the correct image that is in the pictureBox.
But the second one cropped is all white and empty.
And i call this method from the pictureBox paint event:
private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
{
if (pictureBoxSnap.Image != null)
{
{
if (ClearGraphics == false)
{
if (cropRect == false)
{
if (rectangles[listBoxSnap.SelectedIndex] != Rectangle.Empty)
{
e.Graphics.DrawRectangle(Pens.Firebrick, rectangles[listBoxSnap.SelectedIndex]);
}
}
else
{
if (rect.Width > 10 && rect.Height > 10)
{
e.Graphics.DrawRectangle(Pens.Gray, rect);
pictureBoxSnap.Image = CropImage();
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");
}
}
}
}
}
}
I used a breakpoint on the: e.Graphics.DrawRectangle(Pens.Gray, rect); and rect is not empty ( rect is Rectangle i draw on the pictureBox then when i click on a button it's making validate for the pictureBox).
I also did a save here too and testimageing i see it black on the hard disk but when i edit it with Paint i see it's white empty.
For exmaple when i draw a rectangle on the pictureBox then i use a breakpoint in the CropImage method i see that the variable rect is for example: X = 136 Y = 149 Width = 131 Height = 106
Also in the paint event this rect variable have the same values.
And the pictureBox size is: 640x480
And the pictureBox property SizeMode is set to: zoom
Wo why i get empty white image ? And not the cropped rectangle with the part of the image inside ?
EDIT:
This is the code im using now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DannyGeneral;
using System.Diagnostics;
namespace MinimizeCapture
{
public partial class Form1 : Form
{
Boolean bHaveMouse;
Point ptOriginal = new Point();
Point ptLast = new Point();
bool cropRect;
Bitmap cloneBitmap;
Rectangle recttest;
private Rectangle Rect;
private Rectangle[] rectangles;
private Rectangle RectClone;
private bool btn = false;
private Point RectStartPoint = Point.Empty;
private Point RectEndPoint = Point.Empty;
private Brush selectionBrush = new SolidBrush(Color.Red);
private Pen pen;
private string selectedIndex;
private List<string> drawnItems = new List<string>();
private bool ClearGraphics;
public Form1()
{
InitializeComponent();
cropRect = false;
var windows = OpenWindowGetter.FindWindowsWithText();
ClearGraphics = false;
this.DoubleBuffered = true;
btn = false;
pen = new Pen(selectionBrush);
buttonSnap.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void buttonSnap_Click(object sender, EventArgs e)
{
ClearGraphics = true;
this.listBoxSnap.Items.Clear();
this.pictureBoxSnap.Image = null;
backgroundWorker1.RunWorkerAsync();
}
private void listBoxSnap_SelectedIndexChanged(object sender, EventArgs e)
{
WindowSnap snap = this.listBoxSnap.SelectedItem as WindowSnap;
selectedIndex = this.listBoxSnap.SelectedIndex.ToString();
this.pictureBoxSnap.Image = snap.Image;
for (int i = 0; i < rectangles.Length; i++)
{
if (rectangles[i] != RectClone)
{
ClearGraphics = false;
}
else
{
ClearGraphics = true;
}
}
}
private void checkBoxForceMDI_CheckedChanged(object sender, EventArgs e)
{
WindowSnap.ForceMDICapturing = (sender as CheckBox).Checked;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.Add("Minimized Windows"); }));
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true,true).ToArray()); }));
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
rectangles = new Rectangle[listBoxSnap.Items.Count];
buttonSnap.Enabled = true;
}
private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
{
if (pictureBoxSnap.Image != null)
{
{
if (ClearGraphics == false)
{
if (rectangles[listBoxSnap.SelectedIndex] != Rectangle.Empty)
{
e.Graphics.DrawRectangle(Pens.Firebrick, rectangles[listBoxSnap.SelectedIndex]);
}
}
if (cropRect == true)
{
if (recttest.Width > 10 && recttest.Height > 10)
{
//e.Graphics.DrawRectangle(Pens.Gray, recttest);
e.Graphics.Clear(Color.White);
/*pictureBoxSnap.Image = CropImage();
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");*/
}
}
}
}
}
private void pictureBoxSnap_MouseMove(object sender, MouseEventArgs e)
{
if (btn == true)
{
ClearGraphics = false;
RectEndPoint = e.Location;
int currentindex = listBoxSnap.SelectedIndex;
rectangles[currentindex] = RectClone;
Rect = getRect(RectStartPoint, RectEndPoint);
RectClone = Rect;
pictureBoxSnap.Invalidate();
}
Point ptCurrent = new Point(e.X, e.Y);
// If we "have the mouse", then we draw our lines.
if (bHaveMouse)
{
// If we have drawn previously, draw again in
// that spot to remove the lines.
if (ptLast.X != -1)
{
MyDrawReversibleRectangle(ptOriginal, ptLast);
}
// Update last point.
ptLast = ptCurrent;
// Draw new lines.
MyDrawReversibleRectangle(ptOriginal, ptCurrent);
}
}
private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
{
RectStartPoint = e.Location;
btn = true;
Rect = Rectangle.Empty;
RectClone = Rectangle.Empty;
bHaveMouse = true;
// Store the "starting point" for this rubber-band rectangle.
ptOriginal.X = e.X;
ptOriginal.Y = e.Y;
// Special value lets us know that no previous
// rectangle needs to be erased.
ptLast.X = -1;
ptLast.Y = -1;
}
private void pictureBoxSnap_MouseUp(object sender, MouseEventArgs e)
{
recttest = rectangles[listBoxSnap.SelectedIndex];
ClearGraphics = false;
btn = false;
RectEndPoint = e.Location;
pictureBoxSnap.Invalidate();
int currentindex = listBoxSnap.SelectedIndex;
rectangles[currentindex] = RectClone;
// Set internal flag to know we no longer "have the mouse".
bHaveMouse = false;
// If we have drawn previously, draw again in that spot
// to remove the lines.
if (ptLast.X != -1)
{
Point ptCurrent = new Point(e.X, e.Y);
MyDrawReversibleRectangle(ptOriginal, ptLast);
}
// Set flags to know that there is no "previous" line to reverse.
ptLast.X = -1;
ptLast.Y = -1;
ptOriginal.X = -1;
ptOriginal.Y = -1;
pictureBoxSnap.Invalidate();
}
Rectangle getRect(Point p1, Point p2)
{
Point p = new Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
Size s = new Size(Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y));
return new Rectangle(p, s);
}
private void ConfirmRectangle_Click(object sender, EventArgs e)
{
ConfirmRectangle.ForeColor = Color.Red;
ConfirmRectangle.Enabled = false;
StreamWriter w = new StreamWriter(#"c:\temp\Settings.txt", true);
w.WriteLine("Rectangle Location: " + RectClone.Location + " Rectangle Size: " + RectClone.Size + " Selected Index: " + selectedIndex);
textBoxIndex.Text = selectedIndex.ToString();
w.Close();
cropRect = false;
//pictureBoxSnap.Invalidate();
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;
}
// Convert and normalize the points and draw the reversible frame.
private void MyDrawReversibleRectangle(Point p1, Point p2)
{
Rectangle rc = new Rectangle();
// Convert the points to screen coordinates.
p1 = pictureBoxSnap.PointToScreen(p1);
p2 = pictureBoxSnap.PointToScreen(p2);
// Normalize the rectangle.
if (p1.X < p2.X)
{
rc.X = p1.X;
rc.Width = p2.X - p1.X;
}
else
{
rc.X = p2.X;
rc.Width = p1.X - p2.X;
}
if (p1.Y < p2.Y)
{
rc.Y = p1.Y;
rc.Height = p2.Y - p1.Y;
}
else
{
rc.Y = p2.Y;
rc.Height = p1.Y - p2.Y;
}
// Draw the reversible frame.
rect = new Rectangle(pictureBoxSnap.PointToClient(rc.Location), rc.Size);
ControlPaint.DrawReversibleFrame(rc, Color.Gray, FrameStyle.Dashed);
}
Rectangle rect = Rectangle.Empty;
private Bitmap CropImage()
{
//rect = recttest;
Bitmap pic = pictureBoxSnap.Image as Bitmap;
Bitmap cropped = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(cropped))
{
g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
rect, GraphicsUnit.Pixel);
}
pic.Save(#"c:\temp\testingitimage.jpg");
cropped.Save(#"c:\temp\testingitimage1.bmp");
return cropped;
}
}
}
Moved the CropImage call method from the paint and added it to the button click here:
private void ConfirmRectangle_Click(object sender, EventArgs e)
{
ConfirmRectangle.ForeColor = Color.Red;
ConfirmRectangle.Enabled = false;
StreamWriter w = new StreamWriter(#"c:\temp\Settings.txt", true);
w.WriteLine("Rectangle Location: " + RectClone.Location + " Rectangle Size: " + RectClone.Size + " Selected Index: " + selectedIndex);
textBoxIndex.Text = selectedIndex.ToString();
w.Close();
cropRect = false;
//pictureBoxSnap.Invalidate();
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;
}
This lines:
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;
But what i get in the pictureBox is this:
Not sure why. The rectangle is in the position i drawed it's ok but instead showing the part of the original image cut in the rectangle it's doing like zoom in.
You are cropping multiple times.
pictureBoxSnap.Image = CropImage(); // First Time
Image img = CropImage(); // Second Time
img.Save(#"c:\temp\testimageing.jpg");
You just need to crop once. Here you are using same picturebox for source and for cropped image. first time when you crop then image. the cropped image will be set correctly to the picturebox. but, second time application will try to crop that image again.
You should do like this
Image img = CropImage();
img.Save(#"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;
private Bitmap CropImage(){
Bitmap pic = pictureBoxSnap.Image as Bitmap;
Bitmap cropped = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(cropped)){
g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
rect, GraphicsUnit.Pixel);
}
using (Graphics g = Graphics.FromImage(pic)){
g.DrawImage(cropped , 136, 149, rect.Width, rect.Height);
//Draw the rectangle
}
//pic.Save(#"c:\temp\testingitimage.jpg");
//cropped.Save(#"c:\temp\testingitimage1.bmp");
return pic;
}
valter

C# Save modified image in panel

I am attempting to save an image as modified by graphics tools such as pens and shapes that can be drawn onto the image. I have done this using a panel with background image and trying to set up a bit map that will save changes within this panel:
private void saveToolStripButton_Click(object sender, EventArgs e)
{
//sets panel1 contents as bit map to be saved at set locations
int width = panel1.Size.Width;
int height = panel1.Size.Height;
using (Bitmap bmp = new Bitmap(width, height))
{
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, width, height));
bmp.Save(#"C:\Users\Me\Pics\testBitmap.jpeg", ImageFormat.Jpeg);
}
MessageBox.Show("Your image has been saved");
}
Once the save button is clicked, the image saves ok but the changes made with the graphics tools do not show up. Can anyone suggest a solution?
Here is some code regarding the graphics tool i've set up for use within the panel:
{
InitializeComponent();
//Create graphics object in panel1
g = panel1.CreateGraphics();
}
private void btnExit2_Click(object sender, EventArgs e)
{
this.Close();
}
Graphics g;
//set a drawing boolean
bool draw = false;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
draw = true;
if (drawSq)
{
SolidBrush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
if (toolStripTextBox1.Text != "")
{
g.FillRectangle(brush, e.X, e.Y, Convert.ToInt32(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox1.Text));
}
else if (toolStripTextBox1.Text == "")
{
MessageBox.Show("Please enter a shape size");
}
draw = false;
drawSq = false;
}
}
and more:
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
mouseX = null;
mouseY = null;
}
//null values allow freehand style drawing
int? mouseX = null;
int? mouseY = null;
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
//creates a pen tool and sets properties by mouse location
if (draw)
{
Pen pen = new Pen(btnColor.ForeColor, float.Parse(txtBox1.Text));
g.DrawLine(pen, new Point(mouseX ?? e.X, mouseY ?? e.Y), new Point(e.X, e.Y));
mouseX = e.X;
mouseY = e.Y;
}
}
Let's try to fix this.
Start by creating your image first:
Bitmap bmp;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
}
Now when you want to draw on it:
void panel1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
using (Graphics g = Graphics.FromImage(bmp)) {
g.FillEllipse(Brushes.Red, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
}
panel1.Invalidate();
}
}
And display the results:
void panel1_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawImage(bmp, Point.Empty);
}
To save, just use your bitmap:
bmp.Save(#"c:\filename.png", ImageFormat.Png);
Use Double buffering with Panel to avoid the flickering.
This will works fine. I tested it and worked well........
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace drawing
{
public partial class Form2 : Form
{
Graphics g;
bool startPaint = false;
int? initX = null;
int? initY = null;
bool drawSquare = false;
bool drawRectangle = false;
bool drawCircle = false;
public Form2()
{
InitializeComponent();
bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
}
Bitmap bmp;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (startPaint)
{
using ( g = Graphics.FromImage(bmp))
{
// g.FillEllipse(Brushes.Black, new Rectangle(e.X, e.Y , 5, 5));
Pen p = new Pen(btn_PenColor.BackColor, float.Parse(cmb_PenSize.Text));
g.DrawLine(p, new Point(initX ?? e.X, initY ?? e.Y), new Point(e.X, e.Y));
initX = e.X;
initY = e.Y;
//g.DrawImage(bmp, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
}
panel1.Invalidate();
}
}
private void pnl_Draw_MouseDown(object sender, MouseEventArgs e)
{
startPaint = true;
if (drawSquare)
{
//Use Solid Brush for filling the graphic shapes
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
//setting the width and height same for creating square.
//Getting the width and Heigt value from Textbox(txt_ShapeSize)
g.FillRectangle(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
//setting startPaint and drawSquare value to false for creating one graphic on one click.
startPaint = false;
drawSquare = false;
}
if (drawRectangle)
{
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
//setting the width twice of the height
g.FillRectangle(sb, e.X, e.Y, 2 * int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
startPaint = false;
drawRectangle = false;
}
if (drawCircle)
{
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
g.FillEllipse(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
startPaint = false;
drawCircle = false;
}
}
private void pnl_Draw_MouseUp(object sender, MouseEventArgs e)
{
startPaint = false;
initX = null;
initY = null;
}
void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(bmp, Point.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
bmp.Save("D://filename.jpg", ImageFormat.Png);
}
}
}

Draw rectangle C# Mouse_down working Mouse_up not

I want to draw an rectangle on an form the mouse_down event is working fine, but how do i programm the mouse_up. Should how do i dertermine the starting coordinates.
http://oi49.tinypic.com/2wcnof8.jpg
Rectangle rect = new Rectangle();
Color rastercolor = Color.Black;
private void drawGrid(Color rastercolor)
{
Graphics gfx = this.CreateGraphics();
Pen pen = new Pen(rastercolor);
for (int i = 0; i <= 2000; i = i + 20)
{
gfx.DrawLine(pen, 0, i, 2000, i);
}
for (int x = 0; x < 2000; x = x + 20)
{
gfx.DrawLine(pen, x, 0, x, 2000);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
rect = new Rectangle(e.X, e.Y, 0, 0);
if (e.Button == MouseButtons.Middle)
{
ColorDialog coldial = new ColorDialog();
coldial.ShowDialog();
Color rastercolor = coldial.Color;
tekenGrid(rastercolor);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
}
}
protected override void OnPaint(PaintEventArgs e)
{
tekenGrid(rastercolor);
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
private void Frm1_MouseUp(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Red, 2);
g.DrawRectangle(pen, rect);
}
private void Frm1_Load(object sender, EventArgs e)
{
}
private void Frm1_MouseDown(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Blue, 2);
g.DrawRectangle(pen, rect);
}
}
}
Any help would be greatly appreciated,
Not sure if this is what you are upto. Please try this code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle rect = new Rectangle();
Color _rastercolor = Color.Black;
private Pen _pen=new Pen(Color.Red,2);
private void tekenGrid(Color rastercolor, Graphics gfx)
{
Pen pen = new Pen(rastercolor);
for (int i = 0; i <= 2000; i = i + 20)
{
gfx.DrawLine(pen, 0, i, 2000, i);
}
for (int x = 0; x < 2000; x = x + 20)
{
gfx.DrawLine(pen, x, 0, x, 2000);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
rect = new Rectangle(e.X, e.Y, 0, 0);
if (e.Button == MouseButtons.Middle)
{
ColorDialog coldial = new ColorDialog();
coldial.ShowDialog();
Color rastercolor = coldial.Color;
tekenGrid(rastercolor,this.CreateGraphics());
}
else
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
this.Refresh();
}
base.OnMouseMove(e);
}
protected override void OnPaint(PaintEventArgs e)
{
tekenGrid(_rastercolor,e.Graphics);
e.Graphics.DrawRectangle(_pen, rect);
}
private void Frm1_MouseUp(object sender, MouseEventArgs e)
{
_pen = new Pen(Color.Red, 2);
this.Refresh();
}
private void Frm1_Load(object sender, EventArgs e)
{
}
private void Frm1_MouseDown(object sender, MouseEventArgs e)
{
_pen = new Pen(Color.Blue, 2);
}
}

Categories

Resources