[英]How to convert 'System.Windows.Media.Imaging.BitmapImage' to 'System.Drawing.Image'?
[英]How to Convert System.Windows.Media.Imaging.BitmapImage to System.Drawing.Image?
XAML:
<ImageBrush x:Key="Symbol1Brush" ImageSource="Resources\Symbol1.png" Stretch="Uniform" />
編碼:
// In some class
_imageProcessor = new ImageProcessor(Resources["Symbol1Image"] as BitmapImage)
和
public class ImageProcessor
{
private readonly Bitmap _primaryMarkerSymbol;
public ImageProcessor(BitmapImage primaryMarkerSymbol)
{
if (primaryMarkerSymbol == null)
throw new ArgumentNullException("primaryMarkerSymbol");
_primaryMarkerSymbol = new Bitmap(primaryMarkerSymbol.StreamSource);
}
public Bitmap ProcessImage()
{
Graphics g = Graphics.FromImage(img);
g.DrawImage(_primaryMarkerSymbol);
g.Flush();
return img;
}
}
_primaryMarkerSymbol = new Bitmap(primaryMarkerSymbol.StreamSource)拋出異常:'null'的值對'stream'無效。
我假設如果從Resource創建BitmapImage,則不會填充StreamSource。
有什么替代品? 謝謝。
編輯:
關鍵是要使用XAML ResourceDictionary中定義的源對象(例如ImageBrush,BitmapImage)。
您可能需要以某種方式復制位圖的像素:
// test image
BitmapImage image = new BitmapImage(new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"));
// copy to byte array
int stride = image.PixelWidth * 4;
byte[] buffer = new byte[stride * image.PixelHeight];
image.CopyPixels(buffer, stride, 0);
// create bitmap
System.Drawing.Bitmap bitmap =
new System.Drawing.Bitmap(
image.PixelWidth,
image.PixelHeight,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// lock bitmap data
System.Drawing.Imaging.BitmapData bitmapData =
bitmap.LockBits(
new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
bitmap.PixelFormat);
// copy byte array to bitmap data
System.Runtime.InteropServices.Marshal.Copy(
buffer, 0, bitmapData.Scan0, buffer.Length);
// unlock
bitmap.UnlockBits(bitmapData);
這對我來說可以使用資源文件設置圖像源
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);
在構造函數中,我寧願使用它:
System.Windows.Resources.StreamResourceInfo imageInfo = System.Windows.Application.GetResourceStream(primaryMarkerSymbol.UriSource);
_primaryMarkerSymbol = Image.FromStream(imageInfo.Stream);
在一個明確的時刻,我想出了一個我可以提供的解決方案。
我使用BitmapImage.UriSource來獲取相對圖像路徑並加載Image:
public class ImageProcessor
{
private readonly Image _primaryMarkerSymbol;
public ImageProcessor(BitmapImage primaryMarkerSymbol)
{
_primaryMarkerSymbol = Image.FromFile(primaryMarkerSymbol.UriSource.ToString());
}
public Bitmap ProcessImage(string fileName)
{
var img = new Bitmap(fileName);
Graphics g = Graphics.FromImage(img);
g.DrawImage(_primaryMarkerSymbol);
g.Flush();
return img;
}
}
如果我可以使用對象本身在圖形上繪制圖像而不是通過路徑加載,那將是很好的。 所以歡迎你提出一個更好的主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.