WPF ImageBrush 转换
GIF图片
<ImageBrush x:Key="ImageLoadingBrush" >
<ImageBrush.ImageSource>
<BitmapImage UriSource="pack://Application:,,,/chatres;component/Resources/ImageLoading.gif" />
</ImageBrush.ImageSource>
</ImageBrush>
System.Windows.Media.ImageBrush imageBrush = this.Resources["ImageLoadingBrush"] as ImageBrush;
System.Windows.Media.ImageBrush如何转换成System.Drawing.Bitmap?或者Byte[]都可以
[解决办法]
var image = System.Drawing.Image.FromFile("..."); // or wherever it comes from
var bitmap = new System.Drawing.Bitmap(image);
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
bitmap.Dispose();
var brush = new ImageBrush(bitmapSource);
[解决办法]
private void Window_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush imageBrush = this.Resources["ImageLoadingBrush"] as ImageBrush;
var bitmap = GetBitmap(((BitmapSource)imageBrush.ImageSource));
bitmap.Save("E:\\茉莉花.jpg");
}
Bitmap GetBitmap(BitmapSource source)
{
Bitmap bmp = new Bitmap(source.PixelWidth,source.PixelHeight,PixelFormat.Format32bppPArgb);
BitmapData data = bmp.LockBits(new Rectangle(System.Drawing.Point.Empty, bmp.Size),ImageLockMode.WriteOnly,PixelFormat.Format32bppPArgb);
source.CopyPixels(Int32Rect.Empty,data.Scan0,data.Height * data.Stride,data.Stride);
bmp.UnlockBits(data);
return bmp;
}
我注意到你的输入格式是gif。WPF只能显示gif动画的第一帧,如要让它动起来,可参考我的《WPF支持GIF的各种方法》。
上面的代码疑似不能处理gif,jpg是可以的。