1

I am trying to change resolution of my jpg image using c#. I have refer this code that written in this link How to change resolution (DPI) of an image? its work fine but I have getting another issue for grayscale images. if I will try to save grayscale image using this code then it change the bit depth 8 to 24.

So I have try below code but I am getting error like "Bitmap region is already locked". I don't know how to pass guid in GetEncoderParameterList().

    private static ImageCodecInfo GetEncoder(ImageFormat format)
    {

        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }
        return null;
    }

   //Code
   using (Image bitmap = Image.FromFile(pagePath))
        {
            using (Bitmap newBitmap = new Bitmap(bitmap))
            {
                ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
                EncoderParameters para = newBitmap.GetEncoderParameterList(jpgEncoder.Clsid);
                imageResolution = (int)newBitmap.HorizontalResolution;
                newBitmap.SetResolution(250, 250);
                newBitmap.Save("file300.jpg", jpgEncoder, para);
            }
        }

Exception :

enter image description here

Pravin Tukadiya
  • 489
  • 4
  • 20
  • can you please edit your question to include the exact `exception` thrown? – jazb Nov 01 '18 at 06:42
  • Possible duplicate of [Unexpected "Bitmap Region is already Locked" exception with GetEncoderParameterList. Any ideas?](https://stackoverflow.com/questions/3152506/unexpected-bitmap-region-is-already-locked-exception-with-getencoderparameterl) – Access Denied Nov 01 '18 at 06:47
  • @AccessDenied I have try this one but its give me another exception like "File not found" – Pravin Tukadiya Nov 01 '18 at 06:48
  • see https://stackoverflow.com/questions/21346211/bitmap-region-is-already-locked – Genish Parvadia Nov 01 '18 at 06:53
  • I am not comparing images. I am try to change resolution of image and save it. but when I try to save gray-scale images its change automatically to RGB. so I am try to assigning same encode parameter for gray-scale but it throws an error. – Pravin Tukadiya Nov 01 '18 at 06:57
  • I can confirm this bug. – Access Denied Nov 01 '18 at 07:59
  • 1
    Not all __defined__ pixelformats are actually __supported__. 24bit grayscale is not. Not all GDI+ error messages are to the points. This may not be.. – TaW Nov 01 '18 at 08:24
  • 8-bit jpeg does not exist on GDI+ and gets converted to 24-bit on load. If all you want to do is edit the EXIF data, I suggest you look into the EXIF specs and parse the binary format to edit it. – Nyerguds Nov 13 '18 at 14:14
  • @TaW no, they said their 8-bit grayscale gets converted to 24-bit, which is normal RGB. – Nyerguds Nov 13 '18 at 14:17

0 Answers0