using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SelectImageRectangle
{
    public partial class frm38SelectImageRectangle : Form
    {
        public frm38SelectImageRectangle()
        {
            InitializeComponent();
        }

        // The original image.
        private Bitmap OriginalImage;

        // True when we're selecting a rectangle.
        private bool IsSelecting = false;

        // The drags starting point.
        private Point StartPoint;

        // Start selecting the rectangle.
        private void originalPictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            IsSelecting = true;

            // Copy the original image.
            OriginalImage = new Bitmap(originalPictureBox.Image);

            // Save the start point.
            StartPoint = e.Location;
        }

        // Continue selecting.
        private void originalPictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            // Do nothing it we're not selecting an area.
            if (!IsSelecting) return;

            // Make a Bitmap to display the selection rectangle.
            Bitmap bm = new Bitmap(OriginalImage);
            using (Graphics gr = Graphics.FromImage(bm))
            {
                // Draw the rectangle.
                Rectangle rect = GetRectangle(StartPoint, e.Location);
                using (Pen pen = new Pen(Color.Red, 3))
                {
                    gr.DrawRectangle(pen, rect);
                }
            }

            // Display the temporary bitmap.
            originalPictureBox.Image = bm;
        }

        // Finish selecting the area.
        private void originalPictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            // Do nothing it we're not selecting an area.
            if (!IsSelecting) return;
            IsSelecting = false;

            // Display the original image.
            originalPictureBox.Image = OriginalImage;

            // Copy the selected part of the image.
            Rectangle rect = GetRectangle(StartPoint, e.Location);
            Bitmap area = ImagePiece(OriginalImage, rect);

            // Display the result.
            resultPictureBox.Image = area;
            resultPictureBox.Show();
        }

        // Return a Rectangle with the two points as opposite corners.
        private Rectangle GetRectangle(Point point1, Point point2)
        {
            int x = Math.Min(point1.X, point2.X);
            int y = Math.Min(point1.Y, point2.Y);
            int width = Math.Abs(point2.X - point1.X);
            int height = Math.Abs(point2.Y - point1.Y);
            return new Rectangle(x, y, width, height);
        }

        // Return a piece of an image.
        private Bitmap ImagePiece(Bitmap bm, Rectangle sourceRect)
        {
            // Intersect the rectangle with the Bitmap's bounds.
            Rectangle bmRect = new Rectangle(0, 0, bm.Width, bm.Height);
            sourceRect.Intersect(bmRect);

            // Make sure the result has a positive size.
            if ((sourceRect.Width < 1) || (sourceRect.Height < 1)) return null;
            
            Bitmap piece = new Bitmap(sourceRect.Width, sourceRect.Height);
            using (Graphics gr = Graphics.FromImage(piece))
            {
                Rectangle destRect = new Rectangle(0, 0,
                    sourceRect.Width, sourceRect.Height);
                gr.DrawImage(bm, destRect,
                    sourceRect, GraphicsUnit.Pixel);
            }
            return piece;
        }


        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.resultPictureBox = new System.Windows.Forms.PictureBox();
            this.originalPictureBox = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.resultPictureBox)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.originalPictureBox)).BeginInit();
            this.SuspendLayout();
            // 
            // resultPictureBox
            // 
            this.resultPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.resultPictureBox.Location = new System.Drawing.Point(318, 12);
            this.resultPictureBox.Name = "resultPictureBox";
            this.resultPictureBox.Size = new System.Drawing.Size(0, 0);
            this.resultPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.resultPictureBox.TabIndex = 3;
            this.resultPictureBox.TabStop = false;
            this.resultPictureBox.Visible = false;
            // 
            // originalPictureBox
            // 
            this.originalPictureBox.Cursor = System.Windows.Forms.Cursors.Cross;
            this.originalPictureBox.Image = global::SelectImageRectangle.Properties.Resources.sw_eng;
            this.originalPictureBox.Location = new System.Drawing.Point(12, 12);
            this.originalPictureBox.Name = "originalPictureBox";
            this.originalPictureBox.Size = new System.Drawing.Size(300, 375);
            this.originalPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.originalPictureBox.TabIndex = 2;
            this.originalPictureBox.TabStop = false;
            this.originalPictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.originalPictureBox_MouseDown);
            this.originalPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.originalPictureBox_MouseMove);
            this.originalPictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.originalPictureBox_MouseUp);
            // 
            // frm38SelectImageRectangle
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(406, 399);
            this.Controls.Add(this.resultPictureBox);
            this.Controls.Add(this.originalPictureBox);
            this.Name = "frm38SelectImageRectangle";
            this.Text = "SelectImageRectangle";
            ((System.ComponentModel.ISupportInitialize)(this.resultPictureBox)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.originalPictureBox)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.PictureBox resultPictureBox;
        private System.Windows.Forms.PictureBox originalPictureBox;
    }
}