c# Bitmap 转bitmapImage高效方法

网上有很多人都记录以下方法进行转换,这个方法存在一个问题,就是低效,我在进行图片拼接时,图片大了之后就会很慢。所以我有找了一个高效的替代方法。

 public BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            System.Drawing.Bitmap bitmapSource = new System.Drawing.Bitmap(bitmap.Width, bitmap.Height);
            int i, j;
            for (i = 0; i < bitmap.Width; i++)
                for (j = 0; j < bitmap.Height; j++)
                {
                    System.Drawing.Color pixelColor = bitmap.GetPixel(i, j);
                    System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B);
                    bitmapSource.SetPixel(i, j, newColor);
                }
            MemoryStream ms = new MemoryStream();
            bitmapSource.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(ms.ToArray());
            bitmapImage.EndInit();

            return bitmapImage;
        }

这种方法快多了。赶紧快去试试吧:

public BitmapImage ToBitmapImage(System.Drawing.Bitmap ImageOriginal)
        {

            System.Drawing.Bitmap ImageOriginalBase = new System.Drawing.Bitmap(ImageOriginal);
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                ImageOriginalBase.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }

 

你可能感兴趣的:(c#,WPF,windows,Bitmap,BitmapImage,c#)