我已经在xaml代码中创建了Image对象:
<Image Name="Square" Source="Square.png" Height="400" Width="640"/>
在后面的代码中,我写了:
WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);
如果我要创建像素数组,则将其放在WritableBitmap中,然后放入Image中,如下所示:
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'?
Square.Source = bitmap;
bitmap = Square.Source; // Why it does not work?
谢谢你的帮助。
您不能直接WriteableBitmap
从any创建一个ImageSource
,因为mayImageSource
可能不是a BitmapSource
(Writeablebitmap构造函数将其作为参数)。
但是,根据您的情况,可以将该Source
属性强制转换为BitmapSource
:
var bitmap = new WriteableBitmap((BitmapSource)Square.Source);
请注意,Source
Image控件的属性属于ImageSource
(而不是BitmapSource
)类型,因为该控件不仅可以显示位图(例如矢量图像),还可以显示其他类型的图像。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句