Tuesday 24 December 2013

Simple Image Resizer Tools - C# Example

Leave a Comment
This example will use the  Image Resizer Class from previous post. I have change a little bit on the class so that i can use it for my example image resizer tools.

ImageResizer Tool Requirement

  • ImageResizer tool will require user to choose the image to resize.
  • Only JPG image supported.
  • After that user can simply put the width and height to change the selected image width and height.
  • User can choose is either to use aspect ratio.
  • After Complete , user will prompt to open the new image after resize.
  • The tools use .NET version 4.

The GUI of ImageResizer Tool

The Code Behind

        private string _ImageName;
        private string _ImageExtension;

        public Form1()
        {
            InitializeComponent();
            TPercentage.Text = "0";
            tWidth.Text = "0";
            THeight.Text = "0";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "JPEG Files (.JPG)|*.JPG";
            openFileDialog1.FilterIndex = 1;

            openFileDialog1.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            DialogResult Dr = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (Dr.ToString().Equals("OK",StringComparison.CurrentCultureIgnoreCase))
            {
                TSelectImage.Text = openFileDialog1.FileName;
                _ImageName = (openFileDialog1.FileName.Split('\\'))[openFileDialog1.FileName.Split('\\').Length - 1];
                _ImageExtension = _ImageName.Substring(_ImageName.Length - 4);
                loadImage();
            }
        }

        protected void loadImage(string filename = "")
        {
            panel1.Visible = true;
            pictureBox1.WaitOnLoad = false;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            if(filename == "")
                pictureBox1.LoadAsync(openFileDialog1.FileName);
            pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
        }

        void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //label3.Text = pictureBox1.Image.Width.ToString();
            //label5.Text = pictureBox1.Image.Height.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string reSizeImageName = _ImageName + "_Resize" + _ImageExtension;
            long width = Convert.ToInt64(tWidth.Text);
            long height = Convert.ToInt64(THeight.Text);
            double percentageRatio = Convert.ToDouble(TPercentage.Text);
           

        AGAIN:
            ImageResizer.ResizeImage(pictureBox1.ImageLocation, Directory.GetCurrentDirectory() + "\\" + reSizeImageName,
                100,percentageRatio,width,height,checkBox1.Checked);

            if (ImageResizer.Status == 1)           
                goto AGAIN;//this is because method need to run in async which is not supported in .NET 4 ..only support .NET 4.5 currently


            DialogResult dr = MessageBox.Show("Resize succes, open file in an external viewer?", "Open File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "\\" + reSizeImageName);
            }           

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                label2.Visible = false;
                label3.Visible = false;
                tWidth.Visible = false;

                label4.Visible = false;
                label5.Visible = false;
                THeight.Visible = false;

                label6.Visible = true;
                TPercentage.Visible = true;
                label7.Visible = true;
                TPercentage.Text = "0";
                tWidth.Text = "0";
                THeight.Text = "0";
            }
            else
            {
                label2.Visible = true;
                label3.Visible = true;
                tWidth.Visible = true;

                label4.Visible = true;
                label5.Visible = true;               
                THeight.Visible = true;

                label6.Visible = false;
                TPercentage.Visible = false;
                label7.Visible = false;
                tWidth.Text = "0";
                THeight.Text = "0";
                TPercentage.Text = "0";
            }
        }

        private void TPercentage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }



The Modified ImageResizer Class

class ImageResizer
    {
        private static ImageCodecInfo jpgEncoder;
        private static int _status;

        public static int Status
        {
            get { return ImageResizer._status; }
            set { ImageResizer._status = value; }
        }

        /// <summary>
        /// Method to resize JPEG and GIF Image
        /// </summary>
        /// <param name="inFile">input file location</param>
        /// <param name="outFile">output file location</param>
        /// <param name="level"> level of compression between 0 and 100, with 0 being maximum compression and minimum size and 
        /// with 100 being minimum compression and maximum size.(For JPEG Only)</param>
        /// <param name="maxDimension">percentage ratio</param>
        /// <param name="newWidth">width of new image</param>
        /// <param name="newHeight">height of new image</param>
        /// <param name="useAspectRatio">true | false</param>
        public static void ResizeImage(string inFile, string outFile, long level,double maxDimension = 0, long newWidth = 0, long newHeight = 0,bool useAspectRatio = false)
        {       
        
            byte[] buffer;
            using (Stream stream = new FileStream(inFile, FileMode.Open))
            {
                buffer = new byte[stream.Length];
                Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
            }

            try
            {
                using (MemoryStream memStream = new MemoryStream(buffer))
                {
                    using (Image inImage = Image.FromStream(memStream))
                    {
                        double width = 0;
                        double height = 0;

                        if (newWidth > 0)
                            width = Convert.ToDouble(newWidth);
                        if (newHeight > 0)
                            height = Convert.ToDouble(newHeight);

                        if (useAspectRatio)
                        {
                            width = inImage.Width * (maxDimension / 100);
                            height = inImage.Height * (maxDimension / 100);                            
                        }

                        using (Bitmap bitmap = new Bitmap((int)width, (int)height))
                        {
                            using (Graphics graphics = Graphics.FromImage(bitmap))
                            {
                                graphics.SmoothingMode = SmoothingMode.HighQuality;
                                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                graphics.DrawImage(inImage, 0, 0, bitmap.Width, bitmap.Height);
                                if (inImage.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                                {
                                    if (jpgEncoder == null)
                                    {
                                        ImageCodecInfo[] ici = ImageCodecInfo.GetImageDecoders();
                                        foreach (ImageCodecInfo info in ici)
                                        {
                                            if (info.FormatID == ImageFormat.Jpeg.Guid)
                                            {
                                                jpgEncoder = info;
                                                break;
                                            }
                                        }
                                    }
                                    if (jpgEncoder != null)
                                    {
                                        EncoderParameters ep = new EncoderParameters(1);
                                        ep.Param[0] = new EncoderParameter(Encoder.Quality, level);
                                        bitmap.Save(outFile, jpgEncoder, ep);
                                    }
                                    else
                                    {
                                        bitmap.Save(outFile, inImage.RawFormat);
                                    }
                                }
                                else
                                {
                                    //
                                    // Fill with white for transparent GIFs
                                    //
                                    graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);
                                    bitmap.Save(outFile, inImage.RawFormat);

                                }                                
                                Status = 0;
                            }
                        }
                    }
                }
            }
            catch (ArgumentException arg)
            {
                if (arg.Message.Equals("Parameter is Not Valid.", StringComparison.CurrentCultureIgnoreCase))
                    Status = 1;
                else
                    MessageBox.Show(arg.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "." + Environment.NewLine + "Please Try Again");
            }
        }
       
    }



Have a try ..Do PM me in Google+ to share the project.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.