using System.Drawing;

namespace ZionGraphics.Filtering
{
    class Quality : IFilter
    {
        private System.Drawing.Imaging.ImageCodecInfo GetEncoder(System.Drawing.Imaging.ImageFormat format)
        {
            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders();
            foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
        public override Bitmap Apply(Bitmap bitmap)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1);
                System.Drawing.Imaging.EncoderParameter parameter = new System.Drawing.Imaging.EncoderParameter(encoder, Intensity);

                parameters.Param[0] = parameter;

                Bitmap ajusted = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat);
                ajusted.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
                ajusted.Save(stream, jpgEncoder, parameters);

                ajusted = new Bitmap(System.Drawing.Image.FromStream(stream));
                ajusted.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);

                return ajusted;
            }
        }
    }
}
