Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

.net - System.Drawing.Bitmap to JPEG XR

How can I encode a System.Drawing.Bitmap (v4.0) to the JPEG XR stream?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be solved through an extension method:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

/// <remarks>
/// Requires reference to <c>System.Drawing</c>, <c>PresentationCore</c> and <c>WindowsBase</c>.
/// </remarks>
public static class JpegXr {

    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);
    }

    /// <seealso cref="http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap"/>
    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();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...