[Silverlight] 使用WritableBitmap 將圖片處理成為黑白圖片..

2010/10/13

之前遇到我們家設計一個小要求... 他需要一個轉把圖片轉黑白的特效...

在Silverlight 中要如何做到呢?!

下面是小範例... 先介紹一下配置..
 sshot-1

點擊按鈕後可以將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 是一個微軟全球性計畫,藉者提供軟體跟技術支援跟資源幫助創業家跟創業公司穩健成長..
相關請參考:
bzspark

備註2:
身為一個專業的Silverlight 的開發人員..桌面應該要….
sshot-2
要有小光…哈哈…

讚一下:

檔案下載:


0 意見:

程式 . 生活 . D小調.@2010 | Binary Design: One Winged Angel.