Search code examples
c#imageimage-conversionimage-formats

How to change Image file formats


I want to write an application that takes an image(jpeg, png, tiff, gif,...) as stream and convert it to jrx(jpeg xr) with lossless compression.

Thats is what i have tried so far with no useable result:

using System.Windows.Media.Imaging;
    //decode jpg
    public static BitmapSource ReadJpeg(Stream imageStreamSource)
    {
        JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bitmapSource = decoder.Frames[0];
        return bitmapSource;
    }
    //encode
    public static Stream Encode(BitmapSource image)
    {
        WmpBitmapEncoder encoder = new WmpBitmapEncoder();
        MemoryStream s = new MemoryStream();
        encoder.Frames.Add(BitmapFrame.Create(image));
        encoder.Save(s);
        return s;
    }

Can someone point me in the right direction? I am hanging here for some time now.

If you need more informations please ask.

System.Drawing.Bitmap to JPEG XR is working for the given input formats but doesnt fully cover my question because the part of decoding the image is missing.

Thank you all for pointing me in the right direction! I do know now, how to proceed.


Solution

  • try this:

    public static MemoryStream SaveJpegXr(this Bitmap bitmap, float quality) 
        {
            var stream = new MemoryStream();
            SaveJpegXr(bitmap, quality, stream);
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
    
        public static void SaveJpegXr(this Bitmap bitmap, float quality, Stream output) 
         {
            var bitmapSource = bitmap.ToWpfBitmap();
            var bitmapFrame = BitmapFrame.Create(bitmapSource);
            var jpegXrEncoder = new WmpBitmapEncoder();
            jpegXrEncoder.Frames.Add(bitmapFrame);
            jpegXrEncoder.ImageQualityLevel = quality / 100f;
            jpegXrEncoder.Save(output);
        }
    
    
        public static BitmapSource ToWpfBitmap(this Bitmap bitmap)
     {
            using (var stream = new MemoryStream()) 
            {
                bitmap.Save(stream, ImageFormat.Bmp);
                stream.Position = 0;
                var result = new BitmapImage();
                result.BeginInit();
    
    
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }