首页 > 解决方案 > 在c#中从位图转换为ImageBitmap的问题

问题描述

当我将两个像素位图转换为图像位图时,我将其更改为具有许多像素的普通图像并将其转换为渐变(黑色和白色像素现在是从黑色到灰色到白色的渐变)

public static BitmapImage Bitmap2BitmapImage(this Bitmap bitmap)
{
    using (var memory = new MemoryStream())
    {
        bitmap.Save(memory, ImageFormat.Png);
        memory.Position = 0;

        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();
        bitmapImage.Freeze();

        return bitmapImage;
    }
}

标签: c#image

解决方案


更新:这是一种Bitmap无需平滑即可缩放 a 的方法。

        public static Bitmap Scale(int count, Bitmap source)
    {
        if (count <= 0) { return source; }
        var bitmap = new Bitmap(source.Size.Width * count, source.Size.Height * count);
        var sourcedata = source.LockBits(new Rectangle(new System.Drawing.Point(0, 0), source.Size), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        var bitmapdata = bitmap.LockBits(new Rectangle(new System.Drawing.Point(0, 0), bitmap.Size), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        unsafe
        {
            var srcByte = (byte*)sourcedata.Scan0.ToPointer();
            var dstByte = (byte*)bitmapdata.Scan0.ToPointer();
            for (var y = 0; y < bitmapdata.Height; y++) {
                for (var x = 0; x < bitmapdata.Width; x++) {
                    long index = (x / count) * 4 + (y / count) * sourcedata.Stride;
                    dstByte[0] = srcByte[index];
                    dstByte[1] = srcByte[index + 1];
                    dstByte[2] = srcByte[index + 2];
                    dstByte[3] = srcByte[index + 3];
                    dstByte += 4;
                }
            }
        }
        source.UnlockBits(sourcedata);
        bitmap.UnlockBits(bitmapdata);

        return bitmap;
    }

在这种情况下,你可以得到正确BitmapSource的:

   var bitmapSrc = MyImagingHelper.Scale(100,twoPixelBitmap)//this will get a Bitmap size 200 * 100,change the ratio if it is not enough
   .ToBitmapSource();//Convert to bitmap source

如果您只想将一个Bitmap转换BitmapSource为在 WPF 控件中显示,请尝试以下方法:

    [DllImport("gdi32", EntryPoint = "DeleteObject")]
    public static extern bool DeleteHBitmap(IntPtr hObject);        


    public static BitmapSource ToBitmapSource(this Bitmap target)
    {
        var hbitmap = target.GetHbitmap();
        try {
            return Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        finally {
            DeleteHBitmap(hbitmap);
        }
    }

不要忽略 DeleteHBitmap 调用!


推荐阅读