how to compress image in c

Solutions on MaxInterview for how to compress image in c by the best coders in the world

showing results for - "how to compress image in c"
Roberta
09 May 2016
1public static void CompressImage(string sourcepath, string destpath, int quality)
2{
3    var FileName = Path.GetFileName(sourcepath);
4    destpath = destpath + "\\" + FileName;
5    using (Bitmap bmpl = new Bitmap(sourcepath))
6    {
7        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
8        System.Drawing.Imaging.Encoder QualityEncoder = System.Drawing.Imaging.Encoder.Quality;
9        EncoderParameters myEncoderParameters = new EncoderParameters(1);
10        EncoderParameter myEncoderParameter = new EncoderParameter(QualityEncoder, quality);
11        myEncoderParameters.Param[0] = myEncoderParameter;
12        bmpl.Save(destpath, jpgEncoder, myEncoderParameters);
13    }
14}
15
16private static ImageCodecInfo GetEncoder(ImageFormat format)
17{
18    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
19    foreach(ImageCodecInfo codec in codecs)
20    {
21        if(codec.FormatID==format.Guid)
22        {
23            return codec;
24        }
25    }
26    return null;
27}
28
29private void button3_Click(object sender, EventArgs e)
30{
31    string[] files = Directory.GetFiles(textBox1.Text);
32    DialogResult result2 = folderBrowserDialog1.ShowDialog();
33    if (result2 == DialogResult.OK)
34    {
35        foreach (var file in files)
36        {
37            string ext = Path.GetExtension(file).ToUpper();
38            if (ext == ".PNG" || ext == ".JPG")
39            {
40                CompressImage(file, folderBrowserDialog1.SelectedPath, (int)comboBox1.SelectedItem);
41            }
42            else
43            {
44                MessageBox.Show("The selected file: " + textBox1.Text + " does not contain no imege.", "Compress Unsuccessfull!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
45                ClassGV.image = 1;
46                break;
47            }
48        }
49        if (ClassGV.image != 1)
50        {
51            MessageBox.Show("Compressed images has been stored to\n" + folderBrowserDialog1.SelectedPath, "Compress Successfull!", MessageBoxButtons.OK, MessageBoxIcon.Information);
52        }
53    }
54}