8,735
社区成员
发帖
与我相关
我的任务
分享
<Grid x:Name="LayoutRoot" Background="White">
<Image Height="65" HorizontalAlignment="Left" Margin="69,76,0,0" Name="imgSource" Stretch="Fill" VerticalAlignment="Top" Width="137" Source="test.jpg" />
<Button Content="转为黑白" Height="28" HorizontalAlignment="Left" Margin="217,113,0,0" Name="btnConvertBnW" VerticalAlignment="Top" Width="76" FontSize="14" Click="btnConvertBnW_Click" />
<Image Height="65" HorizontalAlignment="Left" Margin="307,76,0,0" Name="imgTarget" Stretch="Fill" VerticalAlignment="Top" Width="137" />
</Grid>
private void btnConvertBnW_Click(object sender, RoutedEventArgs e)
{
//读取想转换的图片并转为WritableBitmap
WriteableBitmap bitmap = new WriteableBitmap(this.imgSource, null);
for (int y = 0; y < bitmap.PixelHeight; y++)
{
for (int x = 0; x < bitmap.PixelWidth; x++)
{
//获取每一个像素
int pixelLocation = bitmap.PixelWidth * y + x;
int pixel = bitmap.Pixels[pixelLocation];
byte[] pixBytes = BitConverter.GetBytes(pixel);
//每一个都除3
byte bnwPixel = (byte)(.333 * pixBytes[2] + .333 * pixBytes[1] + .333 * pixBytes[0]);
pixBytes[0] = bnwPixel;//b
pixBytes[1] = bnwPixel;//g
pixBytes[2] = bnwPixel;//r
//将处理后的像素返回
bitmap.Pixels[pixelLocation] = BitConverter.ToInt32(pixBytes, 0);
}
}
//显示结果
this.imgTarget.Source = bitmap;
}