2014-01-08 163 views
1

我有一個位圖正在執行着色轉換。我有像素的新陣列,但我不知道那麼如何將其保存到磁盤圖像將位圖像素陣列保存爲新的位圖

public static void TestProcessBitmap(string inputFile, string outputFile) 
    { 
     Bitmap bitmap = new Bitmap(inputFile); 
     Bitmap formatted = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format8bppIndexed); 

     byte[] pixels = BitmapToPixelArray(formatted); 

     pixels = Process8Bits(pixels, System.Windows.Media.Colors.Red); 

     Bitmap output = new Bitmap(pixels); //something like this 
    } 

我怎樣才能然後保存新的像素作爲磁盤上的一個位圖?

+1

記得妥善處理你的位圖。 http://stackoverflow.com/questions/5838608/net-and-bitmap-not-automatically-disposed-by-gc-when-there-is-no-memory-left – geedubb

回答

2

我相信你可以使用Bitmap.Save()方法,你已經將字節加載回Bitmap對象。 This post可能會給你一些關於如何做到這一點的見解。

According to this MSDN document,如果你只在使用Bitmap.Save()指定路徑,

如果沒有編碼器存在的圖像文件格式,使用便攜式 網絡圖形(PNG)編碼器。

+0

在這種情況下,我在內存中的流是的位圖中的實際像素,而不是文件本身 – jimmyjambles

1

您可以使用MemoryStream將字節數組轉換爲位圖,然後將其提供給Image.FromStream方法。你的例子是這樣的..

public static void TestProcessBitmap(string inputFile, string outputFile) 
{ 
    Bitmap bitmap = new Bitmap(inputFile); 
    Bitmap formatted = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format8bppIndexed); 

    byte[] pixels = BitmapToPixelArray(formatted); 

    pixels = Process8Bits(pixels, System.Windows.Media.Colors.Red); 

    using (MemoryStream ms = new MemoryStream(pixels)) 
    { 
     Bitmap output = (Bitmap)Image.FromStream(ms); 
    } 
} 
+0

+1 - 似乎是比我提到的文章更簡單的方法。 – OnoSendai

+0

我不太確定這必然是一個更簡單的方法,但實現了不同的目的。這個答案只是從一個字節數組創建一個位圖對象,而Bitmap.Save()需要一個位圖,並將其保存到文件或流中。 –

+0

不要誤解我的意思,我認爲簡單更好。我的意思是這一個 - http://stackoverflow.com/questions/6782489/create-bitmap-from-a-byte-array-of-pixel-data – OnoSendai