0

this is my first time asking in stackoverlow and sorry for my messy english

I always got this error message while trying to save the images

Exception popup screenshot

it said "a generic error occurred in gdi+.". I'm trying to save compressed images in the source folder

Here is my code

 public static void CompressImage(string SoucePath, int quality)
        {
            var FileName = Path.GetFileName(SoucePath);
            var DestPath = SoucePath + "\\" + FileName;

            using (Bitmap bmp1 = new Bitmap(SoucePath))
            {
                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;
                bmp1.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;
        }
  • 1
    Post the *full error text* in the question itself. Images can't be copied, googled or compiled. The exception text contains the location where the exception was thrown and the calls that led to it. Right now, we have no way of knowing which line in the code threw – Panagiotis Kanavos Sep 18 '20 at 09:52
  • There is a CopyDetails in that error message, please dont use screenshots. – CSharpie Sep 18 '20 at 09:55
  • For all one knows, the file path may be wrong, because the folder path already contains a trailing backslash. You should use `Path.Combine(SoucePath , FileName)` instead of `SoucePath + "\\" + FileName`. The application account may not have permission to write to the target folder. `FileName` may be a relative path pointing to an invalid folder, eg `..\..\Images\someImage.jpg` may point to the `Images` project folder during debugging, but a completely different location at runtime – Panagiotis Kanavos Sep 18 '20 at 09:57
  • @PanagiotisKanavos thanks! it works now :'D now i need to find a way to delete the old files – The Uncrown Sep 21 '20 at 03:26

0 Answers0