开发者社区> 杰克.陈> 正文

【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 string,color,brush之间的转换
原文:c#-WPF string,color,brush之间的转换 String转换成Color string-"ffffff" Color color = (Color)ColorConverter.
1446 0
[uwp]ImageSource和byte[]相互转换
原文:[uwp]ImageSource和byte[]相互转换 最近做一个小app遇到一个问题,到目前还没有比较好的解决方法(可能是我查的资料不够多) 需求如下: 1.把一个Image中的图像保存到字节数组; 2.把字节数组转换为ImageSource,通过Image控件展示图像. 上面两个需求恰恰是相反的过程,为了实现这个,我倒网上找了好多,但基本都是wp7,wp8,wpf的方案,在win10上没法用。
1257 0
Wpf ImageSource对象与Bitmap对象的互相转换
原文:Wpf ImageSource对象与Bitmap对象的互相转换 Bitmap to ImageSource 将得到的Bitmap对象转换为wpf常用的Imagesource对象 BitmapSource bs = Imaging.
1969 0
+关注
杰克.陈
一个安静的程序猿~
文章
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载