Dies ist eine alternative Technik, die die gleiche Sache tut. Die angenommene Antwort funktioniert, aber ich bekam Probleme mit Bildern, die Alpha-Kanäle hatten (selbst nach dem Wechsel zu PngBitmapEncoder). Diese Technik kann auch schneller sein, da sie nach der Umwandlung in ein kompatibles Pixelformat nur eine Rohkopie von Pixeln erstellt.
public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
{
//convert image format
var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
src.BeginInit();
src.Source = bitmapsource;
src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
src.EndInit();
//copy to bitmap
Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data);
return bitmap;
}
Es gibt ein Problem: Sie verlieren die Transparenz (für eine Bitmap mit Alphakanal). – sibvic