接上一篇文章,在WPF中对图形进行操作,上一篇文章中使用了ImageSource (BitmapSource)中的两种:
1、使用BitmapImage加载图片2、使用 RenderTargetBitmap创建图片3、使用RenderTargetBitmap修改图片
本 文继续
4、使用WriteableBitmap修改图片
在使用 RenderTargetBitmap修改图片中,原图片不变,只相当于在原图片的基础上添加 一节新的内容,而如果对图片进行大的更改RenderTargetBitmap就不可以了,我 们可以使用WriteableBitmap对图片进行修改,例如将生成一个返向位图:
1: <Window x:Class="WPF_28.Window1"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
5: <Grid>
6: <Grid.RowDefinitions>
7: <RowDefinition Height="1*" />
8: <RowDefinition Height="1*" />
9: </Grid.RowDefinitions>
10: <Image Grid.Row="0" x:Name="sourceImage" Source="http://images.cnblogs.com/logo.gif" />
11: <Image Grid.Row="1" x:Name="targetImage" />
12: </Grid>
13: </Window>
1: private void BuildImage()
2: {
3: BitmapImage img = new BitmapImage();
4: img.BeginInit();
5:
6: img.UriSource = new Uri ("http://images.cnblogs.com/logo.gif");
7:
8: img.DownloadCompleted += delegate
9: {
10: BitmapSource source = new FormatConvertedBitmap(
11: img, PixelFormats.Pbgra32, null, 0);
12:
13: WriteableBitmap bmp = new WriteableBitmap(source);
14:
15: int width = bmp.PixelWidth;
16: int height = bmp.PixelHeight;
17:
18: int[] pixelData = new int[width * height];
19: int widthInBytes = 4 * width;
20:
21: bmp.CopyPixels(pixelData, widthInBytes, 0);
22:
23: for (int i = 0; i < pixelData.Length; i++)
24: {
25: pixelData[i] ^= 0x00ffffff;
26: }
27:
28: bmp.WritePixels(new Int32Rect(0, 0, width, height), pixelData, widthInBytes, 0);
29:
30: targetImage.Source = bmp;
31: };
32:
33: img.EndInit();
34: }
35:
36: private void Window_Loaded(object sender, RoutedEventArgs e)
37: {
38: BuildImage();
39: }
执行后的 结果如下图所示: