WPF允許使用Image元素顯示位圖,然而,按這種方法顯示圖片的方法完全是單向的,應用程式使用現成的位圖,讀取問題,并在視窗中顯示位圖,就其本身而言,Image元素沒有提供創建和編輯位圖資訊的方法,
這正是WriteableBitmap類的用武之地,該類繼承自BitmapSource,BitmapSource類是當設定Image.Source屬性時使用的類(不管是在代碼中直接設定影像,還是在XAML中隱式地設定影像),但BitmapSource是只讀的位圖資料映射,而WriteableBitmap類是可修改的像素陣列,為實作許多有趣得效果提供了可能,
一、生成位圖
為使用WriteableBitmap類生成一幅位圖,必須提供提供幾部分重要資訊:以像素為單位的寬度和高度、兩個方向上的DPI解析度以及影像格式,
下面是創建一幅與當前影像元素尺寸相同的位圖的示例:
// 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、Gray2、Gray4、Gray8,這些格式是黑白和灰度格式,單詞Gray后面的數字和每像素的位置相對應,因此,這些格式是壓縮的,但它們不支持顏色,
- Indexed1、Indexed2、Indexed4、Indexed8,這些是索引格式,這意味著每個像素指向顏色調色板中的一個值,當使用這些格式中的某種格式時,必須做出WriteableBitmap建構式的最后一個引數傳遞相應的ColorPalette物件,單詞Indexed后面的數字和每像素的位數相對應,索引格式是壓縮的,使用這些格式稍微復雜一些,并且分別支持更少的顏色——2、4、16以及256種顏色,
前三種格式——Bgra32、Bgr32以及Pbgra32——是最常見的選擇,
二、寫入WriteableBitmap物件
開始時,WriteableBitmap物件中所有位元組的值都是0,本質上,就是一個大的黑色的矩形,為使用內容填充WriteableBitmap物件,需要使用WritePixels()方法,WritePixels()方法將位元組陣列復制到指定位置的位圖中,可呼叫WritePixels()方法設定單個像素、整幅位圖或選擇的某塊矩形區域,為從WriteableBitmap物件中獲取像素,需要使用CopyPixels()方法,該方法將希望獲取的多個位元組轉換成位元組陣列,總之,WritePixels()和CopyPixels()方法沒有提供可供使用的最方便編程模型,但這是低級像素訪問需要付出的代價,
為成功地使用WritePixels()方法,需要理解影像格式并需要理解如何將像素編碼到位元組,例如,在Bgra32型別的32位位圖中,每個像素需要4個位元組,每個位元組分別用于藍、綠、紅以及alpha成分,下面的代碼顯示了如何手動設定這些數值,然后將它們轉換成陣列:
int alpha = 0; int red = 0; int green = 0; int blue = 0; byte[] colorData=https://www.cnblogs.com/Peter-Luo/p/{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 = https://www.cnblogs.com/Peter-Luo/p/{ (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物件中的像素,從而可以構建更特殊的用于位圖編輯以及位圖命中測驗的例程,
三、更高效的像素寫入
盡管上一節中顯示的代碼可以作業,但并非最佳方法,如果需要一次性寫入大量像素資料——甚至是整幅影像——最好使用更大的塊,因為呼叫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 = https://www.cnblogs.com/Peter-Luo/p/{ (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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4478.html
標籤:WPF
