2011-11-10 48 views
3

灰度圖像這是我的位圖碼保存位圖圖像,如C#

Bitmap b = new Bitmap(columns, rows, PixelFormat.Format24bppRgb); 
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat); 

我怎麼能這樣保存爲灰度圖像?

嗯iam特別感興趣的保存部分。我如何將它保存爲文件?

回答

-3
+2

雖然這可能在理論上回答這個問題,但[這將是更可取的](http://meta.stackexchange.com/q/8259)在這裏包含答案的基本部分,並提供供參考的鏈接。 –

+0

鏈接只有沒有上下文或解釋的答案是非常脆弱的。鏈接腐爛離開其他用戶不知道什麼是在另一端。 – Kev

+0

鏈接不可用 - 這將是很好的輸入代碼的主要部分在這裏 –

1

我已經使用了類似的方法,以在此之前

http://www.codeproject.com/KB/graphics/quickgrayscale.aspx

例如:

  for (int Y = 0; Y < Size.Y; Y++) 
      { 
       PixelData_s* PPixel = 
        PixelAt(0, Y, ImageWidth, PBase); 

       for (int X = 0; X < Size.X; X++) 
       { 
        byte Value = (byte)((PPixel->Red + PPixel->Green + PPixel->Blue)/3); 
        PPixel->Red = Value; 
        PPixel->Green = Value; 
        PPixel->Blue = Value; 
        PPixel++; 
       } // End for 
      } // End for 

基本上求和RGB分量值由3給定像素和分頻,這樣需要不安全使用指針進行操作所需的關鍵字。你可以避免使用指針,只是做這樣的事情:

 for (int X = 0; X < Size.X; X++) 
     { 
      for (int Y = 0; Y < Size.Y; Y++) 
      { 
       Color C = WinBitmap.GetPixel(X, Y); 
       int Value = (C.R + C.G + C.B)/3; 
       WinBitmap.SetPixel(X, Y, Color.FromArgb(Value, Value, Value)); 
      } // End for 
     } // End for 

但這是比較慢。

1

我發現了一個功能如何在這個地址

How to convert a colour image to grayscale

public Bitmap ConvertToGrayscale(Bitmap source) 
{ 
    Bitmap bm = new Bitmap(source.Width,source.Height); 
    for(int y=0;y<bm.Height;y++) 
    { 
    for(int x=0;x<bm.Width;x++) 
    { 
     Color c=source.GetPixel(x,y); 
     int luma = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11); 
     bm.SetPixel(x,y,Color.FromArgb(luma,luma,luma)); 
    } 
    } 
    return bm; 
} 
+0

以及我更新了我的問題。我不知道如何將其保存爲文件 – user574183

1

我們具有便於衆多「效果」應用,包括簡單的顏色的處理的成像部件 - 它是相當更快地簡單地應用顏色變換矩陣比手動步行逐像素,像所以,例如...

private static ColorMatrix GrayscaleMatrix = new ColorMatrix(
    new float[][] 
    { 
     new float[] {0.30f, 0.30f, 0.30f, 0, 0}, 
     new float[] {0.59f, 0.59f, 0.59f, 0, 0}, 
     new float[] {0.11f, 0.11f, 0.11f, 0, 0}, 
     new float[] {0, 0, 0, 1, 0}, 
     new float[] {0, 0, 0, 0, 1} 
    } 
); 

public static void ApplyGrayscaleTransformation(string inputPath, string outputPath) 
{ 
    using (var image = Bitmap.FromFile(inputPath)) 
    { 
     using (var graphics = Graphics.FromImage(image)) 
     { 
      using (var attributes = new ImageAttributes()) 
      { 
       attributes.SetColorMatrix(GrayscaleMatrix); 
       graphics.DrawImage(image, 
        new Rectangle(0,0,image.Width, image.Height), 
        0, 0, image.Width, image.Height, GraphicsUnit.Pixel, 
        attributes); 
      } 
     } 
     image.Save(outputPath); 
    } 
} 

這個和unsafe方法之間的速度大多是可以忽略不計,但可以變化;當它達到這一點時,值得對它進行測試 - 其中一個好處是不需要使用/unsafe進行編譯。