private void button2_Click(object sender, RoutedEventArgs e)
{
    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
    int startTime = Environment.TickCount;

    int width = bitmapImage.PixelWidth;
    int height = bitmapImage.PixelHeight;
    int stride = width * ((bitmapImage.Format.BitsPerPixel + 7) / 8);
    byte[] pixel = new byte[height * stride];
    
    writeableBitmap.CopyPixels(pixel, stride, 0);

    Parallel.For(0, height, y =>
    {
        int x;

        for (x = 0; x < stride; x++)
        {
            pixel[x + y * stride] = (byte)(255 - pixel[x + y * stride]);
        }
    });

    writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixel, stride, 0);
    image1.Source = writeableBitmap;

    this.Title =(Environment.TickCount - startTime) + " ms";

    //CroppedBitmap
}

  這是WPF對影像做顏色反轉的程式,使用CopyPixels取得每一點的BGRA的byte array之後,用Parallel.For(平行For)進行反轉RGB顏色,然後用WritePixels把處理完後的BGRA array寫回去,然後使用image1顯示出來。

 

  下圖為使用各種方式對影像進行RGB讀寫並反轉色彩,所消耗的時間測試的結果。

 

gdi.png

(使用Bitmap類別中的GetPixel與SetPixel方法)

 

unsafe.png

(使用unsafe 指標直接進行讀寫)

 

parallelUnsafe.png

(使用Parallel.For搭配unsafe指標進行平行直接讀寫)

 

WPF.png  

(使用WPF的WriteableBitmap類別的CopyPixels與WirtePixels進行讀寫)

 

※ 在unsafe Parallel.For 與WPF的時間是第二次的結果,第一次的時間跟使用unsafe的結果相去不遠,反而還比較慢,可能是Parallel.for與WPF在第一次使用時初始化的成本比較高所造成的。

 

測試用Source Code下載

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(1) 人氣()