原文
之前遇到我们家设计一个小要求... 他需要一个转把图片转黑白的特效...
在Silverlight 中要如何做到呢?!
下面是小范例... 先介绍一下配置..
点击按钮后可以将imgSource 的图案转成黑白后放入imgTarget中..
XAML Code:
< UserControl x:Class ="WritableBitmapBnW.MainPage"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d ="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable ="d"
d:DesignHeight ="200" d:DesignWidth ="500" >
< 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 ="bzspark.png" />
< Button Content ="转黑白图" Height ="28" HorizontalAlignment ="Left" Margin ="217,113,0,0" Name ="btnConvertBnW" VerticalAlignment ="Top" Width ="76" FontSize ="14" FontFamily = "微软正黑体" Click ="btnConvertBnW_Click" />
< Image Height ="65" HorizontalAlignment ="Left" Margin ="307,76,0,0" Name ="imgTarget" Stretch ="Fill" VerticalAlignment ="Top" Width ="137" />
</ Grid >
</ UserControl >
来看一下C# 这边的Code..
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++)
{
//取得每一个pixel
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
//位置3是alpha
//排列真是诡异阿..><刚好反过来s
//将处理后的pixel置回
bitmap.Pixels[pixelLocation] = BitConverter.ToInt32(pixBytes, 0);
}
}
//显示结果
this .imgTarget.Source = bitmap;
}
上面有一些地方需要注意..
他的pixelBytes[]排列顺序跟我们平常背的argb 不一样而是bgra很吊诡…
其中如何把图片转黑白做法我有参考此篇.. [C#][VB.NET]彩色图片转为黑白图片
执行结果:
备注1:
BizSpark 是一个微软全球性计画,借者提供软体跟技术支援跟资源帮助创业家跟创业公司稳健成长..
相关请参考:
备注2:
身为一个专业的Silverlight 的开发人员..桌面应该要….
要有小光…哈哈…
赞一下:
档案下载: