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;

using System.Drawing.Imaging;
using System.IO;

namespace OptimizeJpgCompression
{
    public partial class frm35OptimizeJpgCompression : Form
    {
        public frm35OptimizeJpgCompression()
        {
            InitializeComponent();
        }

        // The original uncompressed image.
        private Image OriginalImage = null;

        // Open an image file.
        private void openMenuItem_Click(object sender, EventArgs e)
        {
            if (pictureOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // See how big the file is.
                    originalSizeLabel.Text = FileSize(pictureOpenFileDialog.FileName);

                    // Load the file.
                    OriginalImage = LoadBitmapUnlocked(pictureOpenFileDialog.FileName);

                    // Display a sample image at the current compression level.
                    ShowSampleImage();

                    // Enable the Save As command.
                    saveAsMenuItem.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Load Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // Save the file with the current compression level.
        private void saveAsMenuItem_Click(object sender, EventArgs e)
        {
            if (OriginalImage == null) return;

            if (pictureSaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    long compression = compressionScrollBar.Value;
                    SaveJpg(OriginalImage, pictureSaveFileDialog.FileName, compression);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Save Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // Show a sample image at the selected compression level.
        private void compressionScrollBar_Scroll(object sender, ScrollEventArgs e)
        {
            ShowSampleImage();
        }

        // Display a sample that uses the selected compression index.
        private void ShowSampleImage()
        {
            // Display the compression value.
            long compression = compressionScrollBar.Value;
            compressionLabel.Text = compression.ToString();

            // If no image is loaded, do nothing else.
            if (OriginalImage == null) return;

            // Save the image with the selected compression level.
            string filename = Application.StartupPath + "\\__temp.jpg";
            SaveJpg(OriginalImage, filename, compression);

            // Display the result without locking the file.
            imagePictureBox.Image = LoadBitmapUnlocked(filename);

            // See how big the file is.
            compressedSizeLabel.Text = FileSize(filename);
        }

        // Load a bitmap without locking it.
        private Bitmap LoadBitmapUnlocked(string filename)
        {
            using (Bitmap bm = new Bitmap(filename))
            {
                return new Bitmap(bm);
            }
        }

        // Save the file with a specific compression level.
        private void SaveJpg(Image image, string filename, long compression)
        {
            try
            {
                EncoderParameters encoderParams = new EncoderParameters();
                encoderParams.Param[0] = new EncoderParameter(
                    System.Drawing.Imaging.Encoder.Quality, compression);

                ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
                File.Delete(filename);
                image.Save(filename, codecInfo, encoderParams);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "JPG Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Return an ImageCodecInfo object for this mime type.
        private ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i <= encoders.Length; i++)
            {
                if (encoders[i].MimeType == mimeType) return encoders[i];
            }
            return null;
        }

        // Return a file's size.
        private string FileSize(string filename)
        {
            FileInfo fileinfo = new FileInfo(filename);
            return fileinfo.Length.ToFileSizeApi();
        }


        /// <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.compressedSizeLabel = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.compressionScrollBar = new System.Windows.Forms.HScrollBar();
            this.panel1 = new System.Windows.Forms.Panel();
            this.imagePictureBox = new System.Windows.Forms.PictureBox();
            this.label4 = new System.Windows.Forms.Label();
            this.originalSizeLabel = new System.Windows.Forms.Label();
            this.compressionLabel = new System.Windows.Forms.Label();
            this.Label1 = new System.Windows.Forms.Label();
            this.saveAsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.Label3 = new System.Windows.Forms.Label();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.pictureSaveFileDialog = new System.Windows.Forms.SaveFileDialog();
            this.pictureOpenFileDialog = new System.Windows.Forms.OpenFileDialog();
            this.panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.imagePictureBox)).BeginInit();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // compressedSizeLabel
            // 
            this.compressedSizeLabel.AutoSize = true;
            this.compressedSizeLabel.Location = new System.Drawing.Point(304, 56);
            this.compressedSizeLabel.Name = "compressedSizeLabel";
            this.compressedSizeLabel.Size = new System.Drawing.Size(0, 13);
            this.compressedSizeLabel.TabIndex = 54;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(82, 56);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(45, 13);
            this.label2.TabIndex = 53;
            this.label2.Text = "Original:";
            // 
            // compressionScrollBar
            // 
            this.compressionScrollBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.compressionScrollBar.Location = new System.Drawing.Point(85, 33);
            this.compressionScrollBar.Maximum = 109;
            this.compressionScrollBar.Name = "compressionScrollBar";
            this.compressionScrollBar.Size = new System.Drawing.Size(249, 17);
            this.compressionScrollBar.TabIndex = 52;
            this.compressionScrollBar.Value = 50;
            this.compressionScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this.compressionScrollBar_Scroll);
            // 
            // panel1
            // 
            this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.panel1.AutoScroll = true;
            this.panel1.Controls.Add(this.imagePictureBox);
            this.panel1.Location = new System.Drawing.Point(12, 72);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(350, 276);
            this.panel1.TabIndex = 51;
            // 
            // imagePictureBox
            // 
            this.imagePictureBox.Location = new System.Drawing.Point(0, 0);
            this.imagePictureBox.Name = "imagePictureBox";
            this.imagePictureBox.Size = new System.Drawing.Size(62, 54);
            this.imagePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.imagePictureBox.TabIndex = 19;
            this.imagePictureBox.TabStop = false;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(230, 56);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(68, 13);
            this.label4.TabIndex = 55;
            this.label4.Text = "Compressed:";
            // 
            // originalSizeLabel
            // 
            this.originalSizeLabel.AutoSize = true;
            this.originalSizeLabel.Location = new System.Drawing.Point(133, 56);
            this.originalSizeLabel.Name = "originalSizeLabel";
            this.originalSizeLabel.Size = new System.Drawing.Size(0, 13);
            this.originalSizeLabel.TabIndex = 49;
            // 
            // compressionLabel
            // 
            this.compressionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.compressionLabel.Location = new System.Drawing.Point(337, 35);
            this.compressionLabel.Name = "compressionLabel";
            this.compressionLabel.Size = new System.Drawing.Size(25, 13);
            this.compressionLabel.TabIndex = 46;
            this.compressionLabel.Text = "50";
            this.compressionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Label1
            // 
            this.Label1.AutoSize = true;
            this.Label1.Location = new System.Drawing.Point(12, 35);
            this.Label1.Name = "Label1";
            this.Label1.Size = new System.Drawing.Size(70, 13);
            this.Label1.TabIndex = 45;
            this.Label1.Text = "Compression:";
            // 
            // saveAsMenuItem
            // 
            this.saveAsMenuItem.Enabled = false;
            this.saveAsMenuItem.Name = "saveAsMenuItem";
            this.saveAsMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
            this.saveAsMenuItem.Size = new System.Drawing.Size(163, 22);
            this.saveAsMenuItem.Text = "&Save As...";
            this.saveAsMenuItem.Click += new System.EventHandler(this.saveAsMenuItem_Click);
            // 
            // Label3
            // 
            this.Label3.AutoSize = true;
            this.Label3.Location = new System.Drawing.Point(12, 56);
            this.Label3.Name = "Label3";
            this.Label3.Size = new System.Drawing.Size(30, 13);
            this.Label3.TabIndex = 47;
            this.Label3.Text = "Size:";
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(374, 24);
            this.menuStrip1.TabIndex = 50;
            this.menuStrip1.Text = "menuStrip1";
            // 
            // fileToolStripMenuItem
            // 
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.openMenuItem,
            this.saveAsMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
            this.fileToolStripMenuItem.Text = "File";
            // 
            // openMenuItem
            // 
            this.openMenuItem.Name = "openMenuItem";
            this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
            this.openMenuItem.Size = new System.Drawing.Size(163, 22);
            this.openMenuItem.Text = "&Open...";
            this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
            // 
            // pictureSaveFileDialog
            // 
            this.pictureSaveFileDialog.Filter = "JPG Files|*.jpg";
            // 
            // pictureOpenFileDialog
            // 
            this.pictureOpenFileDialog.Filter = "Graphic Files|*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.tif;*.tiff|All Files|*.*";
            // 
            // frm35OptimizeJpgCompression
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(374, 351);
            this.Controls.Add(this.compressedSizeLabel);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.compressionScrollBar);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.originalSizeLabel);
            this.Controls.Add(this.compressionLabel);
            this.Controls.Add(this.Label1);
            this.Controls.Add(this.Label3);
            this.Controls.Add(this.menuStrip1);
            this.Name = "frm35OptimizeJpgCompression";
            this.Text = "OptimizeJpgCompression";
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.imagePictureBox)).EndInit();
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        internal System.Windows.Forms.Label compressedSizeLabel;
        internal System.Windows.Forms.Label label2;
        private System.Windows.Forms.HScrollBar compressionScrollBar;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.PictureBox imagePictureBox;
        internal System.Windows.Forms.Label label4;
        internal System.Windows.Forms.Label originalSizeLabel;
        internal System.Windows.Forms.Label compressionLabel;
        internal System.Windows.Forms.Label Label1;
        private System.Windows.Forms.ToolStripMenuItem saveAsMenuItem;
        internal System.Windows.Forms.Label Label3;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem openMenuItem;
        private System.Windows.Forms.SaveFileDialog pictureSaveFileDialog;
        private System.Windows.Forms.OpenFileDialog pictureOpenFileDialog;
    }
}