Skip to main content
 首页 » 编程设计

c#之如何将 System.Windows.Media.Imaging.BitmapImage 转换为 System.Drawing.Image

2024年02月23日35txw1958

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 = 新位图(primaryMarkerSymbol.StreamSource) 抛出异常:“null”的值对“stream”无效。

如果 BitmapImage 是从 Resource 创建的,我假设 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);