Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正在将System.Windows.Controls.Image加载到可写位图对象_C#_Wpf_Writeablebitmap - Fatal编程技术网

C# 正在将System.Windows.Controls.Image加载到可写位图对象

C# 正在将System.Windows.Controls.Image加载到可写位图对象,c#,wpf,writeablebitmap,C#,Wpf,Writeablebitmap,我已经用xaml代码创建了图像对象: <Image Name="Square" Source="Square.png" Height="400" Width="640"/> 如果我正在创建像素阵列,将其放入可写位图,然后放入图像,如下所示: int width = 300; int height = 300; WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFo

我已经用xaml代码创建了图像对象:

<Image Name="Square" Source="Square.png" Height="400" Width="640"/>
如果我正在创建像素阵列,将其放入可写位图,然后放入图像,如下所示:

    int width = 300;
    int height = 300;
    WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
    uint[] pixels = new uint[width * height];

    bitmap.WritePixels(new Int32Rect(0, 0, 300, 300), pixels, width * 4, 0);
    **Square.Source = bitmap;**
我没有任何问题,但当我尝试将用xaml代码创建的图像加载到WritableBitmap时,我无法执行以下操作:

WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);
bitmap = Square.Source; // Cannot implicitly convert type 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.WriteableBitmap'
因此,如果我无法将类型“System.Windows.Media.ImageSource”转换为“System.Windows.Media.Imaging.WriteableBitmap”,为什么我可以将“System.Windows.Media.Imaging.WriteableBitmap”转换为“System.Windows.Media.ImageSource”


感谢您的帮助。

您不能从任何
ImageSource
直接创建
WriteableBitmap
,因为
ImageSource
可能不是
BitmapSource
(WriteableBitmap构造函数将其作为参数)

但是,在您的情况下,可以安全地将
属性强制转换为
位图源

var bitmap = new WriteableBitmap((BitmapSource)Square.Source);


请注意,图像控件的
Source
属性的类型为
ImageSource
(而不是
BitmapSource
),因为该控件能够显示位图以外的其他类型的图像,例如矢量图像。

您尝试过类似的操作吗?:
WriteableBitmap WriteableBitmap=new WriteableBitmap(Square.Source);
Hi Sheridan,我已将您的代码置于visual中,但我必须纠正以下错误:“System.Windows.Media.Imaging.WriteableBitmap.WriteableBitmap(System.Windows.Media.Imaging.BitmapSource)”的最佳重载方法匹配'有一些无效参数,参数1:无法从'System.Windows.Media.ImageSource'转换为'System.Windows.Media.Imaging.BitmapSource'啊,对不起,我忘记将
ImageSource
转换为
BitmapSource
。请看@Clemens的回答。谢谢你的回答。它真的帮助了我!
    Square.Source = bitmap;
    bitmap = Square.Source; // Why it does not work?
var bitmap = new WriteableBitmap((BitmapSource)Square.Source);