using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Imaging;


namespace ImageBlockz.Core
{
    /// <summary>
    /// Save image to JPEG format with possibility to set save quality.
    /// </summary>
    public class SaveToJpg
    {
        /// <summary>
        /// Save <see cref="Bitmap"/> to *.jpg file and quality.
        /// </summary>
        /// <param name="bmp">Input <see cref="Bitmap"/></param>
        /// <param name="path">Filename for output.</param>
        /// <param name="quality">Output quality.</param>
        public static void SaveJpg(Bitmap bmp, string path, long quality)
        {
            ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
            Encoder encoder = Encoder.Quality;
            EncoderParameters encoderParams = new EncoderParameters(1);
            EncoderParameter encoderParam = new EncoderParameter(encoder, quality);
            encoderParams.Param[0] = encoderParam;

            if (codecInfo == null)
                return;

            bmp.Save(path, codecInfo, encoderParams);
        }


        private static 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;
        }
    }
}
