Cutting a rectangular area of an image in C#
From the archive...
Recently, I had to make a simple image cropping tool, so that the user could manually select an area on the source image and cut it out. In principle, nothing complicated, the most difficult thing is probably drawing the selection rectangle when you click the mouse button and move it over the image - highlighting the necessary area.
First, the most important thing. On the image pictureBox immediately set the SizeMode property to AutoSize, without any Zoom-ы if you don't want to deal with scaling.
Next - we need to make it work so that scrolling works when selecting with the mouse. It just so happened that this is a painful place in .NET (it doesn't work on its own, and that's it).
To make it work, do this:
[DllImport("user32.dll")]
public static extern int SendMessage(
int hWnd, // handle to destination window
uint Msg, // message
long wParam, // first message parameter
long lParam // second message parameter
);
And in the event handler:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pic.Width = e.X - begin_x;
pic.Height = e.Y - begin_y;
//Скроллинг...
scroller_hor = -1;
scroller_vert = -1;
if (e.X > panel2.Width - 5)
{ scroller_hor = 0; }
if (e.Y > panel2.Height - 5)
{ scroller_vert = 0; }
}
}
Now - if we move the cursor over the image by clicking the left mouse button, the Scroll-bars will move and the image will shift (in the case where it is larger than the visible area).
Now let's move on to the function that will cut out a piece of the image:
static public Image Copy(Image srcBitmap, Rectangle section)
{
// Вырезаем выбранный кусок картинки
Bitmap bmp = new Bitmap(section.Width, section.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(srcBitmap, 0, 0, section, GraphicsUnit.Pixel);
}
//Возвращаем кусок картинки.
return bmp;
}
Oops - I almost forgot (for all of this) we'll need these variables:
PictureBox pic = new PictureBox(); //Картинка - вырезаемая область.
private int begin_x;
private int begin_y; //Координаты картинки на исходном pictureBox.
bool resize = false; //Эта специальная переменная уберегающая от случайных нажатий мышкой по изображению.
private int scroller_vert = -1;
private int scroller_hor = -1; //Включение выключение скроллинга - таймер проверяет эти значения и посылает сообщения на смещение ScrollBar-ов.
//И вот сам таймер для скроллинга.
private void timer1_Tick(object sender, EventArgs e)
{
if (scroller_vert > -1)
{
SendMessage(panel2.Handle.ToInt32(), 277, 1, scroller_vert);
}
if (scroller_hor > -1)
{
SendMessage(panel2.Handle.ToInt32(), 276, 1, scroller_hor);
}
}
And now, directly about how to draw the frame when selecting, I went for a trick that worked:
//При загрузке формы (но это не обязательно - это у меня так)
private void Form1_Load(object sender, EventArgs e)
{
//Делаем нашей картинке приёмнику родителем картинку источник.
pic.Parent = pictureBox1;
//Теперь делаем её прозрачной но задаём ей рамку BorderStyle.
pic.BackColor = Color.Transparent;
pic.SizeMode = PictureBoxSizeMode.AutoSize;
pic.BorderStyle = BorderStyle.FixedSingle;
pic.Visible = false;
}
Voilà!
It's left to add events for MouseDown and MouseUp (for the initial selection when the mouse button is pressed and the end when released) - do this:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
begin_x = e.X;
begin_y = e.Y;
pic.Left = e.X;
pic.Top = e.Y;
pic.Width = 0;
pic.Height = 0;
pic.Visible = true;
timer1.Start();
resize = true;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
pic.Width = 0;
pic.Height = 0;
pic.Visible = false;
timer1.Stop();
if (resize == true)
{
if ((e.X > begin_x + 10) && (e.Y > begin_y + 10)) //Чтобы совсем уж мелочь не вырезал - и по случайным нажатиям не срабатывал! (можно убрать +10)
{
Rectangle rec = new Rectangle(begin_x, begin_y, e.X - begin_x, e.Y - begin_y);
pictureBox1.Image = Copy(pictureBox1.Image, rec);
}
}
resize = false;
}
That's it, actually.
Comments (0)
No comments yet.