1. 程式人生 > >【C#/WPF】圖像數據格式轉換時,透明度丟失的問題

【C#/WPF】圖像數據格式轉換時,透明度丟失的問題

csdn pypi 數據類型 acc scan str 圖像 ber release

原文:【C#/WPF】圖像數據格式轉換時,透明度丟失的問題

問題:工作中涉及到圖像的數據類型轉換,經常轉著轉著發現,到了哪一步圖像的透明度丟失了!


例如,Bitmap轉BitmapImage的經典代碼如下:

public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
    using (MemoryStream stream = new MemoryStream())
    {
        bitmap.Save
(stream, ImageFormat.Bmp); stream.Position = 0; BitmapImage result = new BitmapImage(); result.BeginInit(); // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." // Force the bitmap to load right now so we can dispose the stream. result.CacheOption
= BitmapCacheOption.OnLoad; result.StreamSource = stream; result.EndInit(); result.Freeze(); return result; } }

使用時發現,如果一張圖片四周是透明的,那麽轉出來的BitmapImage圖像四周透明部分會被自動填充為黑色的!解決辦法在於修改Bitmap保存時選擇的格式,把Bmp改為Png即可。

bitmap.Save(stream, ImageFormat.Png);

同樣,類似的經驗教訓還有如下,在圖片數據格式轉換時,常常要註意是否保留有α通道透明度數據,
比如在ImageSource轉為System.Drawing.Bitmap的方法:

public static System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource)
{
    BitmapSource m = (BitmapSource)imageSource;

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

    System.Drawing.Imaging.BitmapData data = bmp.LockBits(
    new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

    m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
    bmp.UnlockBits(data);

    return bmp;
}

要非常細心,看清楚選擇的格式

System.Drawing.Imaging.PixelFormat.Format32bppPArgb; // 帶有α通道的
System.Drawing.Imaging.PixelFormat.Format32bppRgb;   // 不帶α通道的

【C#/WPF】圖像數據格式轉換時,透明度丟失的問題