Click here to Skip to main content
15,902,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, Recently I add a code to my program to compress images in folder that successfully works. my Question here is how can I compress the Images individually without the need of putting them in a folder via my code?
here is my function:
C#
public static void CompressImage(string sourcepath, string destpath, int quality)
{
    var FileName = Path.GetFileName(sourcepath);
    destpath = destpath + "\\" + FileName;
    using (Bitmap bmpl = new Bitmap(sourcepath))
    {
        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
        System.Drawing.Imaging.Encoder QualityEncoder = System.Drawing.Imaging.Encoder.Quality;
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(QualityEncoder, quality);
        myEncoderParameters.Param[0] = myEncoderParameter;
        bmpl.Save(destpath, jpgEncoder, myEncoderParameters);
    }
}

private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    foreach(ImageCodecInfo codec in codecs)
    {
        if(codec.FormatID==format.Guid)
        {
            return codec;
        }
    }
    return null;
}

private void button3_Click(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles(textBox1.Text);
    DialogResult result2 = folderBrowserDialog1.ShowDialog();
    if (result2 == DialogResult.OK)
    {
        foreach (var file in files)
        {
            string ext = Path.GetExtension(file).ToUpper();
            if (ext == ".PNG" || ext == ".JPG")
            {
                CompressImage(file, folderBrowserDialog1.SelectedPath, (int)comboBox1.SelectedItem);
            }
            else
            {
                MessageBox.Show("The selected file: " + textBox1.Text + " does not contain no imege.", "Compress Unsuccessfull!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ClassGV.image = 1;
                break;
            }
        }
        if (ClassGV.image != 1)
        {
            MessageBox.Show("Compressed images has been stored to\n" + folderBrowserDialog1.SelectedPath, "Compress Successfull!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}


What I have tried:

Well I tried many ways to make my code right, but none of them worked since I can't pinpoint where I have to change to get my desired results. I would appreciate your help.
Posted
Updated 16-Apr-20 4:19am
v2
Comments
[no name] 15-Apr-20 16:22pm    
PNG files are already compressed; compressing "again" won't help. And some "stores" insist on PNG so I convert all my JPG to PNG, which are smaller.

Be aware that PNG and JPEG images are already compressed, and in the case of JPG files it's a lossy compression. Which means that if your compression code is generating a JPG file, it's probably smaller than the input because it has less information in it - which means you threw away detail. Do that too many times, and you will really notice! Similarly, PNG (which is lossless compression) will only reduce in size significantly by discarding info.

I have no idea what your compression is doing, but if it's generation smaller files of the same image, you are losing picture quality or resolution, and you cannot decompress or recover that.

But ... just call CompressImage on the individual file, instead of loading the filenames from the directory and looping.
 
Share this answer
 
Comments
[no name] 16-Apr-20 1:46am    
Hi, well you are right about what the compression is doing, but would you tell me how to call CompressImage on a individual file?
Thank you.
OriginalGriff 16-Apr-20 2:15am    
You are kidding, rght?
You've written a method to "compress"* a file, successfully called it in a loop, and you can't call it without a loop? Are you sure you don;t know how to do that?

CompressImage(@"C:\Temp\MyFileToCompress.jpg", "C:\PlaceToPutIt\", aNumber);

* In this context for "compress" read "destroy".
[no name] 16-Apr-20 2:35am    
Well I'm a rookie in C# & I'm currently researching & studying different matters in programming since I'm in quarantine, & the matter Compression is my interest now. The code above is not mine, I found it in C# corner & I try to understand it ever since. my apologies if my questions seems odd, it's because I'm just a beginner in such subjects. Anyway thank you for helping me.
OriginalGriff 16-Apr-20 4:24am    
If you can't understand what code does - and how it does it - don't use it!
If you don't understand it, how do you know it doesn't install a virus or ransomware on your computer?

Just "grabbing code" isn't a good way to learn, and more than "stealing a Ferrari" is a good way to learn to drive! Instead, get a book - there are free ones out there, google for "C# yellow book" and you'll find one - and go through it cover to cover. That way, you don't miss stuff that you need to understand before you get to more complex bits - like understanding how to call a method that is called in code you "found"! :laugh:
Seriously: a course is the best way to learn, a book is second, desperating hoping that the ability will magically descend upon you is the third, trying to find a youtube video tutorial that actually knows what it is talking about* is fourth, and learning from random code samples is about two hundred and fifty seventh ...




* You won't, they are far too well hidden by all the crap ones, but the search alone will teach you something.
This code snippet:
C#
System.Drawing.Imaging.Encoder.Quality
is how you control compression. The lower the value, the lower the resolution. Valid values are 0-100. If you'll notice, the image has to be in memory (as opposed to in a file) in order to affect the level of compression for the image, and then you need to save it back to disk (maybe with a different filename?).

Here's a link that fully explains the property and its use: Encoder.Quality Field (System.Drawing.Imaging) | Microsoft Docs[^].

You really should make better use of your time by learning how to use google. Furthermore, how can we help you with someone else' code unless you can answer specific questions about it? If you don't understand what it's doing, we generally won't be able to provide effective help.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900