Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

crop image and save

Posted on 2010-09-21
14
1,978 Views
Last Modified: 2013-12-16
Hi EE

I have an image size of 188 x 334px.
i want to crop images on 15x15 px and save it

pls help!

Thank you
public class Form1 : Form
	{
		private OpenFileDialog openFileDialog1;
		private PictureBox pictureBox1;
        private Button btn_browse;
        private Button button1;
		
		private Container components = null;

		public Form1()
		{
			InitializeComponent();
		}

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
                this.pictureBox1.Image = null;
            }

            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

		#region Windows Form Designer generated code
		/// <summary>
		/// Form Design
		/// </summary>
		private void InitializeComponent()
		{
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.btn_browse = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(8, 7);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 50);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // btn_browse
            // 
            this.btn_browse.Location = new System.Drawing.Point(285, 7);
            this.btn_browse.Name = "btn_browse";
            this.btn_browse.Size = new System.Drawing.Size(104, 22);
            this.btn_browse.TabIndex = 1;
            this.btn_browse.Text = "Browse";
            this.btn_browse.Click += new System.EventHandler(this.btn_browse_Click);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(395, 7);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "image scale";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(472, 294);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btn_browse);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.Run(new Form1());
		}

		private void btn_browse_Click(object sender, System.EventArgs e)
		{
			try
			{
                using (OpenFileDialog open = new OpenFileDialog())
                {
                    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

                    open.FilterIndex = 2;
                    open.RestoreDirectory = true;

                    if (open.ShowDialog() == DialogResult.OK)
                    {
                        pictureBox1.Image = new Bitmap(open.FileName);
                    }
                }
			}
			catch (Exception)
			{
				throw new ApplicationException("Failed loading image");
			}
		}

         /// <summary>
        /// image scaling
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int locationX = 300;
                int locationY = 0;
                int cropX = 0;
                int cropY = 0;

                for (int i = 0; i < 5; i++)
                {
                    locationY = 0;
                    locationX = locationX + 40;
                    cropX = cropX + 30;
                    cropY = 0;
                    for (int j = 0; j < 9; j++)
                    {
                        cropY = cropY + 30;
                        locationY = locationY + 40;
                        pictureBox1.Image = cropImage(pictureBox1.Image, new Rectangle(cropX, cropY, 35, 35));
                        //saveJpeg(c:\, pictureBox1.Image, 111);
                        saveJpeg(pictureBox1.Image, 111);

                        this.Controls.Add(pictureBox1);
                        pictureBox1.Image.Dispose();
                        pictureBox1.Image = null;
                    }
                }
            }
            catch (Exception ex){
                MessageBox.Show(ex.Message);
            }
            finally {
                pictureBox1.Image.Dispose();
              }
        }

        //private void saveJpeg(string path, Bitmap img, long quality)
        private void saveJpeg(Image img, int quality)
        {
            try
            {
                //string path = "C:\\Documents and Settings\\Shrestha\\¿¿¿¿¿¿\\load_image\\cropimage\\";
                string path = "C:\\cropimage\\";
                // Encoder parameter for image quality
                System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

                //Jpeg image codec
                System.Drawing.Imaging.ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

                if (jpegCodec == null)
                    return;

                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                img.Save(path, jpegCodec, encoderParams);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// cropping images
        /// </summary>
        private static Image cropImage(Image img, Rectangle cropArea)
        {
            try
            {
                Bitmap bmpImage = new Bitmap(img);
                Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
                bmpImage.Dispose();
                img.Dispose();
                return (Image)(bmpCrop);
                }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private System.Drawing.Imaging.ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
	}

Open in new window

0
Comment
Question by:saloj
  • 5
  • 3
  • 3
  • +1
14 Comments
 
LVL 3

Accepted Solution

by:
ghayasurrehman earned 167 total points
ID: 33723514
do you want to crop it or resize it?

for resize, use this

Image img = ImageFromFile("your location");
Bitmap bmp = new Bitmap(15,15);
Grpahics g = Graphics.FromImage(bmp);
g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, 15, 15), new System.Drawing.Rectangle(0, 0, img.Width, img.Height), System.Drawing.GraphicsUnit.Pixel);



For crop use this

Image img = ImageFromFile("your location");
Bitmap bmp = new Bitmap(15,15);
Grpahics g = Graphics.FromImage(bmp);
g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, 15, 15), new System.Drawing.Rectangle(0, 0, 15, 15), System.Drawing.GraphicsUnit.Pixel);

0
 
LVL 2

Author Comment

by:saloj
ID: 33723540
I have block image which i need to crop into pieces(35x35)px and save each piece as jpg.
here is my complete code which is not working for me.

help!

Thanks
public class Form1 : Form
	{
		private OpenFileDialog openFileDialog1;
		private PictureBox pictureBox1;
        private Button btn_browse;
        private Button button1;
		
		private Container components = null;

		public Form1()
		{
			InitializeComponent();
		}

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
                this.pictureBox1.Image = null;
            }

            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

		#region Windows Form Designer generated code
		/// <summary>
		/// Form Design
		/// </summary>
		private void InitializeComponent()
		{
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.btn_browse = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(8, 7);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 50);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // btn_browse
            // 
            this.btn_browse.Location = new System.Drawing.Point(285, 7);
            this.btn_browse.Name = "btn_browse";
            this.btn_browse.Size = new System.Drawing.Size(104, 22);
            this.btn_browse.TabIndex = 1;
            this.btn_browse.Text = "Browse";
            this.btn_browse.Click += new System.EventHandler(this.btn_browse_Click);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(395, 7);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "image scale";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(472, 294);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btn_browse);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.Run(new Form1());
		}

		private void btn_browse_Click(object sender, System.EventArgs e)
		{
			try
			{
                using (OpenFileDialog open = new OpenFileDialog())
                {
                    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

                    open.FilterIndex = 2;
                    open.RestoreDirectory = true;

                    if (open.ShowDialog() == DialogResult.OK)
                    {
                        pictureBox1.Image = new Bitmap(open.FileName);
                    }
                }
			}
			catch (Exception)
			{
				throw new ApplicationException("Failed loading image");
			}
		}

         /// <summary>
        /// image scaling
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int locationX = 300;
                int locationY = 0;
                int cropX = 0;
                int cropY = 0;

                for (int i = 0; i < 5; i++)
                {
                    locationY = 0;
                    locationX = locationX + 40;
                    cropX = cropX + 30;
                    cropY = 0;
                    for (int j = 0; j < 9; j++)
                    {
                        string imgName = i + "_" + j;
                        cropY = cropY + 30;
                        locationY = locationY + 40;
                        pictureBox1.Image = cropImage(pictureBox1.Image, new Rectangle(cropX, cropY, 35, 35));
                        //saveJpeg(c:\, pictureBox1.Image, 111);
                        saveJpeg(imgName, pictureBox1.Image, 111);

                        this.Controls.Add(pictureBox1);
                        //pictureBox1.Image.Dispose();
                       // pictureBox1.Image = null;
                    }
                }
            }
            catch (Exception ex){
                MessageBox.Show(ex.Message);
            }
            finally {
                pictureBox1.Image.Dispose();
              }
        }

        //private void saveJpeg(string path, Bitmap img, long quality)
        private void saveJpeg(string imgName, Image img, int quality)
        {
            try
            {
                //string path = "C:\\Documents and Settings\\Shrestha\\¿¿¿¿¿¿\\load_image\\cropimage\\";
                string path = "C:\\cropimage\\"+imgName+".jpg";
                // Encoder parameter for image quality
                System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

                //Jpeg image codec
                System.Drawing.Imaging.ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

                if (jpegCodec == null)
                    return;

                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                img.Save(path, jpegCodec, encoderParams);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// cropping images
        /// </summary>
        private static Image cropImage(Image img, Rectangle cropArea)
        {
            try
            {
                Bitmap bmpImage = new Bitmap(img);
                Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
                bmpImage.Dispose();
                img.Dispose();
                return (Image)(bmpCrop);
                }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private System.Drawing.Imaging.ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
	}

Open in new window

0
 
LVL 3

Expert Comment

by:ghayasurrehman
ID: 33723560
use the following function



public void SaveBlock(Image img)
{

int x=0,y=0,i=1;
while(true)
{
if(y>img.Height)
break;
while(true)
{

if(x>img.Width)
break;

Bitmap bmp = new Bitmap(35,35);
Graphics g = Graphics.FromImage(bmp)l
g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, 35, 35), new System.Drawing.Rectangle(0, 0, x+35, y+35), System.Drawing.GraphicsUnit.Pixel);
bmp.Save("block_"+i.ToString());
i++;
x+=35;
}
y+=35;
}

}

Open in new window

0
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 3

Expert Comment

by:ghayasurrehman
ID: 33723565
sorry some changes
public void SaveBlock(Image img)
{

int x=0,y=0,i=1;
while(true)
{
if(y>img.Height)
break;
while(true)
{

if(x>img.Width)
break;

Bitmap bmp = new Bitmap(35,35);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(img, new System.Drawing.Rectangle(0, 0, 35, 35), new System.Drawing.Rectangle(0, 0, x+35, y+35), System.Drawing.GraphicsUnit.Pixel);
bmp.Save("block_"+i.ToString());
i++;
x+=35;
}
y+=35;
}

}

Open in new window

0
 
LVL 2

Author Comment

by:saloj
ID: 33723571
Hi ghayasurrehman,

Thanks for response.

i need help on my code that i put above.

Thanks
0
 
LVL 2

Author Comment

by:saloj
ID: 33723583
here is the image which i would like to crop into pieces.

Thank you
15.JPG
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 167 total points
ID: 33743492
Here is a class that I use to extract images from a composite image.  It borrows from the PicClip concept in VB6.


using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace CSharp.CodeSnippets.Controls
{

    public class PictureClip
    {

        public PictureClip(string fileName)
        {
            m_image = Image.FromFile(fileName);
        }

        private Image m_image;

        public int ClipX { get; set; }
        public int ClipY{ get; set; }
        public int ClipWidth { get; set; }
        public int ClipHeight { get; set; }

        public int Cols
        {
            get { return m_image.Width / this.ClipWidth; }
        }

        public int Rows
        {
            get { return m_image.Height / this.ClipHeight; }
        }

        public Image Clip
        {
            get
            {
                Rectangle sourceRect = new Rectangle(this.ClipX, this.ClipY, this.ClipWidth, this.ClipHeight);

                return this.GetImage(sourceRect);
            }
        }

        public int Cells
        {
            get { return this.Rows * this.Cols; }
        }

        public Image GetGraphicsCell(int index)
        {
            int row = index / this.Rows;
            int col = index % this.Cols;

            Rectangle sourceRect = new Rectangle(col * this.ClipWidth, row * this.ClipHeight, this.ClipWidth, this.ClipHeight);

            return GetImage(sourceRect);
        }

        private Image GetImage(Rectangle sourceRect)
        {

            if (this.ClipWidth <= 0 || this.ClipWidth > m_image.Width)
                throw new ArgumentException("Invalid clip dimensions", "ClipWidth");

            if (this.ClipHeight <= 0 || this.ClipHeight > m_image.Height)
                throw new ArgumentException("Invalid clip dimensions", "ClipHeight");

            Bitmap clipImage = new Bitmap(this.ClipWidth, this.ClipHeight);
            using (Graphics g = Graphics.FromImage(clipImage))
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.DrawImage(m_image, 0, 0, sourceRect, GraphicsUnit.Pixel);
            }
            return clipImage;
        }

    }

}

Open in new window

0
 
LVL 21

Expert Comment

by:surajguptha
ID: 33749652
Saloj, If you could let us know what didn't work in the code snippets provided to you earlier, we would be able to help better.

Thanks
0
 
LVL 2

Author Comment

by:saloj
ID: 33750458
Hi Suraj,

Thank you for response. I am newbie on C# and I am trying to figure out how can i solve it the code that i posted above.
it will be very much helpful i could get complete code.

Thank you
0
 
LVL 21

Assisted Solution

by:surajguptha
surajguptha earned 166 total points
ID: 33755052
Saloj, I used the learned one's code and it seems to be working. I have attached the form consuming his code.

If you want the complete working project, I can email it to you. Please send me your email address.

If this is what you are looking for, please credit learned one points since I used his code to complete the answer to the problem.
Form1.cs
0
 
LVL 21

Expert Comment

by:surajguptha
ID: 33755077
It is just an example implementation. It creates 15 images I think before throwing an exception, you will have to tweek it a little to calculate and use the cell numbers.
0
 
LVL 2

Author Comment

by:saloj
ID: 33786953
Hi Guys,
I am still hanging on the issue and following, i m trying  to explain more cleary to make you understand easily.

In first loop, program successfully run but in next loop it gets error 'System.OutOfMemoryException' occurred in System.Drawing.dll

program flow:
 1st loop
   pictureBox1.Image = 188x334 px (actual img size)
   cropImage = 35x35 px ( crops 35x35 px size)
it successfully crops and saves image "0_0.jpg"

 2nd loop
  pictureBox1.Image = 35x35 px (next loop it shows img 35x35 px size)
  cropImage = 35x35 px
it errors while Cloning the img 'System.OutOfMemoryException' occurred in System.Drawing.dll

In my opinion in 2nd loop pictureBox1.Image display 35x35 px size and try to clone the image and gets error.

hope you can help me to sort it out.

Thank you very much
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Collections.Generic;
namespace load_image
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : Form
	{
		private OpenFileDialog openFileDialog1;
		private PictureBox pictureBox1;
        private Button btn_browse;
        private Button button1;
        private PictureBox pictureBox2;
		
		private Container components = null;

		public Form1()
		{
			InitializeComponent();
		}

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
                this.pictureBox1.Image = null;
                this.pictureBox2.Image.Dispose();
                this.pictureBox2.Image = null;
            }

            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

		#region Windows Form Designer generated code
		/// <summary>
		/// Form Design
		/// </summary>
		private void InitializeComponent()
		{
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.btn_browse = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(8, 7);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 50);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // btn_browse
            // 
            this.btn_browse.Location = new System.Drawing.Point(396, 7);
            this.btn_browse.Name = "btn_browse";
            this.btn_browse.Size = new System.Drawing.Size(75, 19);
            this.btn_browse.TabIndex = 1;
            this.btn_browse.Text = "Browse";
            this.btn_browse.Click += new System.EventHandler(this.btn_browse_Click);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(396, 32);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "Image Scale";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // pictureBox2
            // 
            this.pictureBox2.Location = new System.Drawing.Point(0, 0);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(100, 50);
            this.pictureBox2.TabIndex = 3;
            this.pictureBox2.TabStop = false;
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(472, 294);
            this.Controls.Add(this.pictureBox2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btn_browse);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.Run(new Form1());
		}

		private void btn_browse_Click(object sender, System.EventArgs e)
		{
			try
			{
                using (OpenFileDialog open = new OpenFileDialog())
                {
                    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

                    open.FilterIndex = 2;
                    open.RestoreDirectory = true;

                    if (open.ShowDialog() == DialogResult.OK)
                    {
                        pictureBox1.Image = new Bitmap(open.FileName);
                    }
                }
			}
			catch (Exception)
			{
				throw new ApplicationException("Failed loading image");
			}
		}

         /// <summary>
        /// image scaling
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            //try
            //{
                int locationX = 300;
                int locationY = 0;
                int cropX = 0;
                int cropY = 0;

                for (int i = 0; i < 5; i++)
                {
                    locationY = 0;
                    locationX = locationX + 40;
                    cropX = cropX + 30;
                    cropY = 0;
                    for (int j = 0; j < 9; j++)
                    {
                        string imgName = i + "_" + j;
                        cropY = cropY + 30;
                        locationY = locationY + 40;
                        pictureBox1.Image = pictureBox1.Image;

                        pictureBox1.Image = cropImage(pictureBox1.Image, new Rectangle(cropX, cropY, 35, 35));
                        
                        saveJpeg(imgName, pictureBox1.Image, 111);
                    }
                }
            //}
            //catch (Exception ex){
            //    MessageBox.Show(ex.Message);
            //}

            //finally {
            //    pictureBox1.Image.Dispose();
            //  }
        }

        //private void saveJpeg(string path, Bitmap img, long quality)
        private void saveJpeg(string imgName, Image img, int quality)
        {
            try
            {
                string path = "C:\\cropimage\\"+imgName+".jpg";
                // Encoder parameter for image quality
                System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

                //Jpeg image codec
                System.Drawing.Imaging.ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

                if (jpegCodec == null)
                    return;

                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                img.Save(path, jpegCodec, encoderParams);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// cropping images
        /// </summary>
        private static Image cropImage(Image img, Rectangle cropArea)
        {
            //try
            //{
                Bitmap bmpImage = new Bitmap(img);
            
                Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
                bmpImage.Dispose();
                img.Dispose();
                img = null;
                bmpImage = null;
                return (Image)(bmpCrop);
            //    }
            //catch (Exception ex) {
            //    MessageBox.Show(ex.Message);
            //    return null;
            //}
        }

        private System.Drawing.Imaging.ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
	}
}

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question