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;
}