【WPF學習】第四十七章 WriteableBitmap類

  WPF容許使用Image元素顯示位圖。然而,按這種方法顯示圖片的方法徹底是單向的。應用程序使用現成的位圖,讀取問題,並在窗口中顯示位圖。就其自己而言,Image元素沒有提供建立和編輯位圖信息的方法。編程

  這正是WriteableBitmap類的用武之地。該類繼承自BitmapSource,BitmapSource類是當設置Image.Source屬性時使用的類(不論是在代碼中直接設置圖像,仍是在XAML中隱式地設置圖像)。但BitmapSource是隻讀的位圖數據映射,而WriteableBitmap類是可修改的像素數組,爲實現許多有趣得效果提供了可能。數組

1、生成位圖dom

  爲使用WriteableBitmap類生成一幅位圖,必須提供提供幾部分重要信息:以像素爲單位的寬度和高度、兩個方向上的DPI分辨率以及圖像格式。ide

  下面是建立一幅與當前圖像元素尺寸相同的位圖的示例:函數

// Create the bitmap, with the dimensions of the image placeholder.
            WriteableBitmap wb = new WriteableBitmap((int)img.Width,
                (int)img.Height, 96, 96, PixelFormats.Bgra32, null);

  PixelFormats枚舉提供了許多像素格式,但只有一半格式唄認爲是可寫入的而且獲得了WriteableBitmap類的支持。下面是可供使用的像素格式:性能

  •   Bgra32。這種格式使用32位sRGB顏色。這意味每一個像素由32位(或4個字節)表示。第1個字節表示藍色通道的貢獻(做爲從0到255之間的數字)。第2個字節用於綠色通道,第3個字節用於紅色通道,第4個字節用於alpha值(0表示徹底透明,255表示徹底不透明)。正如可能看到的,顏色的順序(藍綠、紅和alpha)與名稱Bgra32中字母的順序是匹配的。
  •   Bgr32。.這種格式爲每一個像素使用4個字節,就像Bgra32格式同樣。區別是忽略了alpha通道。當不須要透明度時可以使用這種格式。
  •   Pbgra32。就像Bgra32格式同樣,該格式爲每一個像素使用4個字節。區別在於處理半透明像素的方式。爲了提升透明度計算的性能,每一個顏色字節是預先相乘的(所以在Pbgra32中有字母P)。這意味着每一個顏色字節被乘上了alpha值併除以255.在Bgra32格式中具備B、G、R、A值(255,100,0,200)的半透明像素,在Pbgra32格式中變成了(200,78,0,200)。
  •   BlackWhite、Gray二、Gray四、Gray8。這些格式是黑白和灰度格式。單詞Gray後面的數字和每像素的位置相對應。所以,這些格式是壓縮的,但它們不支持顏色。
  •   Indexed一、Indexed二、Indexed四、Indexed8。這些是索引格式,這意味着每一個像素指向顏色調色板中的一個值。當使用這些格式中的某種格式時,必須作出WriteableBitmap構造函數的最後一個參數傳遞相應的ColorPalette對象。單詞Indexed後面的數字和每像素的位數相對應。索引格式是壓縮的,使用這些格式稍微複雜一些,而且分別支持更少的顏色——二、四、16以及256種顏色。

  前三種格式——Bgra3二、Bgr32以及Pbgra32——是最多見的選擇。測試

2、寫入WriteableBitmap對象編碼

  開始時,WriteableBitmap對象中全部字節的值都是0。本質上,就是一個大的黑色的矩形。爲使用內容填充WriteableBitmap對象,須要使用WritePixels()方法。WritePixels()方法將字節數組複製到指定位置的位圖中,可調用WritePixels()方法設置單個像素、整幅位圖或選擇的某塊矩形區域。爲從WriteableBitmap對象中獲取像素,須要使用CopyPixels()方法,該方法將但願獲取的多個字節轉換成字節數組。總之,WritePixels()和CopyPixels()方法沒有提供可供使用的最方便編程模型,但這是低級像素訪問須要付出的代價。spa

  爲成功地使用WritePixels()方法,須要理解圖像格式並須要理解如何將像素編碼到字節。例如,在Bgra32類型的32位位圖中,每一個像素須要4個字節,每一個字節分別用於藍、綠、紅以及alpha成分。下面的代碼顯示瞭如何手動設置這些數值,而後將它們轉換成數組:code

int alpha = 0;
int red = 0;
int green = 0;
int blue = 0;

byte[] colorData={blue,gree,red,alpha};

  須要注意,在此順序是很關鍵的。字節數組必須遵循在Bgra32標準中設置的藍、綠、紅、alpha順序。

  當調用WritePixels()方法時,提供Int32Rect對象以指定位圖中但願更新的矩形區域。Int32Rect封裝了4部分信息:更新區域左上角的X和Y座標,以及更新區域的寬度和高度。

  下面的代碼採用在前面代碼中顯示的colorData數組,並使用該數組設置WriteableBitmap對象中的第一個像素:

// Define the update square (which is as big as the entire image).
Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height);

wb.WritePixels(rect, colorData, 0, 0);

  使用這種方法,可建立生產WriteableBitmap對象的代碼例程。只須要循環處理圖像中的全部列和全部行,並在每次迭代中更新單個像素。

            Random rand = new Random();
            for (int x = 0; x < wb.PixelWidth; x++)
            {
                for (int y = 0; y < wb.PixelHeight; y++)
                {
                    int alpha = 0;
                    int red = 0;
                    int green = 0;
                    int blue = 0;

                    // Determine the pixel's color.
                    if ((x % 5 == 0) || (y % 7 == 0))
                    {
                        red = (int)((double)y / wb.PixelHeight * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)x / wb.PixelWidth * 255);
                        alpha = 255;
                    }
                    else
                    {
                        red = (int)((double)x / wb.PixelWidth * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)y / wb.PixelHeight * 255);
                        alpha = 50;
                    }

                    // Set the pixel value.                    
                    byte[] colorData = { (byte)blue, (byte)green, (byte)red, (byte)alpha }; // B G R

                    Int32Rect rect = new Int32Rect(x, y, 1, 1);
                    int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8;
                    wb.WritePixels(rect, colorData, stride, 0);

                    //wb.WritePixels(.[y * wb.PixelWidth + x] = pixelColorValue;
                }
            }

  上述代碼包含一個額外細節:針對跨距(stride)的計算,WritePixels()方法須要跨距。從技術角度看,跨距是每行像素數據須要的字節數量。可經過將每行中像素的數量乘上所使用格式的每像素位數(一般爲4,如本例使用的Bgra32格式),而後將所得結果除以8,進而將其從位數轉換成字節數。

  完成每一個像素的生產過程後,須要顯示最終位圖。一般將使用Image元素完成該工做:

img.Source = wb;

  即便是在寫入和顯示位圖後,也仍可自由地讀取和修改WriteableBitmap對象中的像素,從而能夠構建更特殊的用於位圖編輯以及位圖命中測試的例程。

3、更高效的像素寫入

  儘管上一節中顯示的代碼能夠工做,但並不是最佳方法。若是須要一次性寫入大量像素數據——甚至是整幅圖像——最好使用更大的塊,由於調用WritePixels()方法須要必定的開銷,而且調用該方法越頻繁,應用程序的運行速度就越慢。

  下圖顯示了一個測試應用程序。該測試程序經過使用沿着規則網格線散步的基本隨機模式填充像素來建立一幅動態位圖。本章示例採用兩種方法執行該任務:使用上一節中國解釋的逐像素方法和稍後介紹看到的一次寫入策略。若是測試該應用程序,將發現一次寫入技術快不少。

 

   爲一次更新多個像素,須要理解像素被打包進字節數組的方式。不管使用哪一種格式,更新緩衝區都將包括一維字節數組。這個數組提供了用於圖像矩形區域中像素的數值,從左向右延伸填充每行,而後自上而下延伸。

  爲找到某個特定像素,須要使用如下公式,下移數行,而後一道該行中恰當的位置:

(x + y * wb.PixelWidth) * BitsPerPixel 

  例如,爲設置一幅Bgra32格式(每一個像素具備4個字節)的位圖中額像素(40,100),須要使用下面的代碼:

int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8;
pixels[pixelOffset] = (byte)blue;
pixels[pixelOffset + 1] = (byte)green;
pixels[pixelOffset + 2] = (byte)red;
pixels[pixelOffset + 3] = (byte)alpha;

  根據上面的方法,下面是建立前面示例的完整代碼,首先在一個數組中填充全部數據,而後值經過一次WritePixels()方法調用將其複製到WriteableBitmap對象中:

// Create the bitmap, with the dimensions of the image placeholder.
            WriteableBitmap wb = new WriteableBitmap((int)img.Width,
                (int)img.Height, 96, 96, PixelFormats.Bgra32, null);

            // Define the update square (which is as big as the entire image).
            Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height);

            byte[] pixels = new byte[(int)img.Width * (int)img.Height * wb.Format.BitsPerPixel / 8];
            Random rand = new Random();
            for (int y = 0; y < wb.PixelHeight; y++)
            {
                for (int x = 0; x < wb.PixelWidth; x++)
                {
                    int alpha = 0;
                    int red = 0;
                    int green = 0;
                    int blue = 0;

                    // Determine the pixel's color.
                    if ((x % 5 == 0) || (y % 7 == 0))
                    {
                        red = (int)((double)y / wb.PixelHeight * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)x / wb.PixelWidth * 255);
                        alpha = 255;
                    }
                    else
                    {
                        red = (int)((double)x / wb.PixelWidth * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)y / wb.PixelHeight * 255);
                        alpha = 50;
                    }

                    int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8;
                    pixels[pixelOffset] = (byte)blue;
                    pixels[pixelOffset + 1] = (byte)green;
                    pixels[pixelOffset + 2] = (byte)red;
                    pixels[pixelOffset + 3] = (byte)alpha;


                }

                int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8;

                wb.WritePixels(rect, pixels, stride, 0);
            }

            // Show the bitmap in an Image element.
            img.Source = wb;

  在實際應用程序中,可選擇折中方法。若是須要更新位圖中一塊較大的區域,不會一次寫入一個像素,由於這種方法的運行速度太慢。但也不會在內存中同時保存所有圖像數據,由於圖像數據可能會很大(畢竟,一幅每像素須要4個字節的1000X1000像素的圖像須要將近4MB的內存,這一要求不會很過度,可是耶比較高)。相反,應當寫入一大塊圖像數據而不是單個像素,當一次生成一整幅位圖時尤爲如此。

本章示例完整標記:

<Window x:Class="Drawing.GenerateBitmap"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GenerateBitmap" Height="460" Width="472" SizeToContent="WidthAndHeight">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Button Content="Button" Grid.Row="1" Height="81" HorizontalAlignment="Left" Margin="106,90,0,0" Name="button1" VerticalAlignment="Top" Width="193" />
        <Button Content="Generate Bitmap" Width="120" Margin="5" Padding="10" Click="cmdGenerate2_Click" HorizontalAlignment="Center"></Button>
        <Image Grid.Row="1" x:Name="img" Margin="5" Width="400" Height="300" IsHitTestVisible="False"></Image>
    </Grid>
</Window>
GenerateBitmap
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Drawing
{
    /// <summary>
    /// GenerateBitmap.xaml 的交互邏輯
    /// </summary>
    public partial class GenerateBitmap : Window
    {
        public GenerateBitmap()
        {
            InitializeComponent();
        }

        private void cmdGenerate_Click(object sender, RoutedEventArgs e)
        {
            // Create the bitmap, with the dimensions of the image placeholder.
            WriteableBitmap wb = new WriteableBitmap((int)img.Width,
                (int)img.Height, 96, 96, PixelFormats.Bgra32, null);

            // Define the update square (which is as big as the entire image).
            Int32Rect rect = new Int32Rect(0, 0, (int)img.Width, (int)img.Height);

            byte[] pixels = new byte[(int)img.Width * (int)img.Height * wb.Format.BitsPerPixel / 8];
            Random rand = new Random();
            for (int y = 0; y < wb.PixelHeight; y++)
            {
                for (int x = 0; x < wb.PixelWidth; x++)
                {
                    int alpha = 0;
                    int red = 0;
                    int green = 0;
                    int blue = 0;

                    // Determine the pixel's color.
                    if ((x % 5 == 0) || (y % 7 == 0))
                    {
                        red = (int)((double)y / wb.PixelHeight * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)x / wb.PixelWidth * 255);
                        alpha = 255;
                    }
                    else
                    {
                        red = (int)((double)x / wb.PixelWidth * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)y / wb.PixelHeight * 255);
                        alpha = 50;
                    }

                    int pixelOffset = (x + y * wb.PixelWidth) * wb.Format.BitsPerPixel / 8;
                    pixels[pixelOffset] = (byte)blue;
                    pixels[pixelOffset + 1] = (byte)green;
                    pixels[pixelOffset + 2] = (byte)red;
                    pixels[pixelOffset + 3] = (byte)alpha;


                }

                int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8;

                wb.WritePixels(rect, pixels, stride, 0);
            }

            // Show the bitmap in an Image element.
            img.Source = wb;
        }

        private void cmdGenerate2_Click(object sender, RoutedEventArgs e)
        {


            // Create the bitmap, with the dimensions of the image placeholder.
            WriteableBitmap wb = new WriteableBitmap((int)img.Width,
                (int)img.Height, 96, 96, PixelFormats.Bgra32, null);

            Random rand = new Random();
            for (int x = 0; x < wb.PixelWidth; x++)
            {
                for (int y = 0; y < wb.PixelHeight; y++)
                {
                    int alpha = 0;
                    int red = 0;
                    int green = 0;
                    int blue = 0;

                    // Determine the pixel's color.
                    if ((x % 5 == 0) || (y % 7 == 0))
                    {
                        red = (int)((double)y / wb.PixelHeight * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)x / wb.PixelWidth * 255);
                        alpha = 255;
                    }
                    else
                    {
                        red = (int)((double)x / wb.PixelWidth * 255);
                        green = rand.Next(100, 255);
                        blue = (int)((double)y / wb.PixelHeight * 255);
                        alpha = 50;
                    }

                    // Set the pixel value.                    
                    byte[] colorData = { (byte)blue, (byte)green, (byte)red, (byte)alpha }; // B G R

                    Int32Rect rect = new Int32Rect(x, y, 1, 1);
                    int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8;
                    wb.WritePixels(rect, colorData, stride, 0);

                    //wb.WritePixels(.[y * wb.PixelWidth + x] = pixelColorValue;
                }
            }

            // Show the bitmap in an Image element.
            img.Source = wb;
        }
    }
}
GenerateBitmap.xaml.cs
相關文章
相關標籤/搜索