【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题

简介: 原文:【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题 C#/WPF项目中,用到图像相关的功能时,涉及到多种图像数据类型的相互转换问题,这里做了个整理。
原文: 【C#/WPF】Bitmap、BitmapImage、ImageSource 、byte[]转换问题

C#/WPF项目中,用到图像相关的功能时,涉及到多种图像数据类型的相互转换问题,这里做了个整理。包含的内容如下:

  • Bitmap和BitmapImage相互转换。
  • RenderTargetBitmap –> BitmapImage
  • ImageSource –> Bitmap
  • BitmapImage和byte[]相互转换。
  • byte[] –> Bitmap

StackOverflow上有很多解决方案,这里选择了试过可行的方法:

  • Bitmap和BitmapImage相互转换
  • 谷歌上搜关键字 C# WPF Convert Bitmap BitmapImage
// Bitmap --> BitmapImage
public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
    using (MemoryStream stream = new MemoryStream())
    {
        bitmap.Save(stream, ImageFormat.Png); // 坑点:格式选Bmp时,不带透明度

        stream.Position = 0;
        BitmapImage 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;
    }
}


// BitmapImage --> Bitmap
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

    using (MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapImage));
        enc.Save(outStream);
        Bitmap bitmap = new Bitmap(outStream);

        return new Bitmap(bitmap);
    }
}
  • RenderTargetBitmap –> BitmapImage
// RenderTargetBitmap --> BitmapImage
public static BitmapImage ConvertRenderTargetBitmapToBitmapImage(RenderTargetBitmap wbm)
{
    BitmapImage bmp = new BitmapImage();
    using (MemoryStream stream = new MemoryStream())
    {
        BmpBitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(wbm));
        encoder.Save(stream);
        bmp.BeginInit();
        bmp.CacheOption = BitmapCacheOption.OnLoad;
        bmp.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        bmp.StreamSource = new MemoryStream(stream.ToArray()); //stream;
        bmp.EndInit();
        bmp.Freeze();
    }
    return bmp;
}


// RenderTargetBitmap --> BitmapImage
public static BitmapImage RenderTargetBitmapToBitmapImage(RenderTargetBitmap rtb)
{
    var renderTargetBitmap = rtb;
    var bitmapImage = new BitmapImage();
    var bitmapEncoder = new PngBitmapEncoder();
    bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

    using (var stream = new MemoryStream())
    {
        bitmapEncoder.Save(stream);
        stream.Seek(0, SeekOrigin.Begin);

        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
    }

    return bitmapImage;
}
  • ImageSource –> Bitmap
// ImageSource --> Bitmap
public static System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource)
{
    BitmapSource m = (BitmapSource)imageSource;

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // 坑点:选Format32bppRgb将不带透明度

    System.Drawing.Imaging.BitmapData data = bmp.LockBits(
    new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

    m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
    bmp.UnlockBits(data);

    return bmp;
}
  • BitmapImage和byte[]相互转换
// BitmapImage --> byte[]
public static byte[] BitmapImageToByteArray(BitmapImage bmp)
{
    byte[] bytearray = null;
    try
    {
        Stream smarket = bmp.StreamSource; ;
        if (smarket != null && smarket.Length > 0)
        {
            //设置当前位置
            smarket.Position = 0;
            using (BinaryReader br = new BinaryReader(smarket))
            {
                bytearray = br.ReadBytes((int)smarket.Length);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    return bytearray;
}


// byte[] --> BitmapImage
public static BitmapImage ByteArrayToBitmapImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; // here
        image.StreamSource = ms;
        image.EndInit();
        image.Freeze();
        return image;
    }
}
  • byte[] –> Bitmap
public static System.Drawing.Bitmap ConvertByteArrayToBitmap(byte[] bytes)
{
    System.Drawing.Bitmap img = null;
    try
    {
        if (bytes != null && bytes.Length != 0)
        {
            MemoryStream ms = new MemoryStream(bytes);
            img = new System.Drawing.Bitmap(ms);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    return img;
}
目录
相关文章
|
C#
浅谈WPF中对控件的位图特效(WPF Bitmap Effects)
原文:浅谈WPF中对控件的位图特效(WPF Bitmap Effects) --------------------------------------------------------------------------------引用或转载时请保留以下信息:大可山 [MSN:a3news(AT)hotmail.
995 0
|
C#
WPF(C#)中Bitmap与BitmapImage相互转换
原文:WPF(C#)中Bitmap与BitmapImage相互转换 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/47296339 ...
4016 0
|
C# 编解码
使用不安全代码将 Bitmap 位图转为 WPF 的 ImageSource 以获得高性能和持续小的内存占用
原文:使用不安全代码将 Bitmap 位图转为 WPF 的 ImageSource 以获得高性能和持续小的内存占用 版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
1141 0
|
C#
WPF Bitmap转imagesource
原文:WPF Bitmap转imagesource 因为WPF中不支持直接显示bitmap格式图片,因此需要对bitmap转换成imagesource再显示。 [System.Runtime.InteropServices.
1074 0
|
C#
GDI+ Bitmap与WPF BitmapImage的相互转换
原文:GDI+ Bitmap与WPF BitmapImage的相互转换 using System.Windows.Interop; //.
965 0
|
存储 C#
[uwp]ImageSource和byte[]相互转换
原文:[uwp]ImageSource和byte[]相互转换 最近做一个小app遇到一个问题,到目前还没有比较好的解决方法(可能是我查的资料不够多) 需求如下: 1.把一个Image中的图像保存到字节数组; 2.把字节数组转换为ImageSource,通过Image控件展示图像. 上面两个需求恰恰是相反的过程,为了实现这个,我倒网上找了好多,但基本都是wp7,wp8,wpf的方案,在win10上没法用。
1391 0
|
C#
Wpf ImageSource对象与Bitmap对象的互相转换
原文:Wpf ImageSource对象与Bitmap对象的互相转换 Bitmap to ImageSource 将得到的Bitmap对象转换为wpf常用的Imagesource对象 BitmapSource bs = Imaging.
2072 0