Wpf Image 展示方式 图片处理 显示

发布于:2024-10-10 ⋅ 阅读:(137) ⋅ 点赞:(0)

Wpf Image 展示方式 图片处理 显示

1、创建Bitmap

   public Bitmap CreateBitmap(int width,int height,int step,IntPtr pdata)
   {
       return new Bitmap(
           width,
           height,
           step,
           System.Drawing.Imaging.PixelFormat.Format8bppIndexed,
           pdata);
   }

2、Bitmap转BitmapSource显示

   public void ShowImg(System.Drawing.Bitmap bitmap)
   {
       IntPtr hBitmap = bitmap.GetHbitmap();
       Img = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
   }

3、Bitmap转BitmapImage显示

   public void ShowImgEx(System.Drawing.Bitmap bitmap)
   {
       MemoryStream ms = new MemoryStream();
       bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
       byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以
       ms.Close();
       BitmapImage image = new BitmapImage();
       image.BeginInit();
       image.StreamSource = new MemoryStream(bytes);
       image.EndInit();
       Img = image; 
       bitmap.Save("111.bmp",ImageFormat.Bmp);
   }

4、WriteableBitmap 显示

public void ShowImgEx2(int width, int height, IntPtr pdata)
{
    var (pixel, palette) = GetPixelFormat(1);
    int bufferLen = width * height;
    BitmapSource? bitmapSource = 
        WriteableBitmap.Create(width, height
        , 96, 96, pixel, palette, pdata, bufferLen, width);
    Img = bitmapSource;
}

public static (System.Windows.Media.PixelFormat, BitmapPalette?) GetPixelFormat(int channel)
{
 var pixel = PixelFormats.Pbgra32;
 BitmapPalette? palette = null;
 switch (channel)
 {
     case 1:
         palette = BitmapPalettes.Gray256;
         pixel = PixelFormats.Indexed8;
         break;
     case 3:
         palette = BitmapPalettes.Gray256;
         pixel = PixelFormats.Bgr24;
         break;
 }

 return (pixel, palette);
}

网站公告

今日签到

点亮在社区的每一天
去签到