c# - 在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;
}
}
解决方案
更新:这是一种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 调用!
推荐阅读
- node.js - Bookshelf.js realtions,如何从第四个表/模型中获取数据?
- android - Google Drive API 出现“无法解析主机”错误
- python - Python - 使用计划模块,使用文件中的参数
- corda - 如何在 Corda 中设置网络地图服务器?
- windows - 如何使用批处理文件杀死特定的 VBScript?
- computational-geometry - 为每个点找到最近线段的高效算法
- erlang - 如何使用 gun:open 在 gen_server 模块中
- php - 删除 PHP 数组的一部分
- react-native - 如何在 react-native 中获取文件的绝对路径?
- stm32 - STM32F103 UART按键事件延迟慢