2017-04-26 33 views
4

我越來越F#從內存流創建位圖拋出異常

System.ArgumentException: 'Parameter is not valid.' 

出於某種原因。

一條線在那裏我得到它:

let image = Bitmap.FromStream stream 

這就是我

let ChangeBitmapColors (bitmap : Bitmap) = 
Console.WriteLine bitmap.Size 

let width = bitmap.Width 
let height = bitmap.Height 

let rectangle = new Rectangle(0, 0, width, height) 

let bitmapData = bitmap.LockBits(rectangle, Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat) 
let length = bitmapData.Stride * height 
let bitmapArray : byte[] = Array.zeroCreate length 

Marshal.Copy(bitmapData.Scan0, bitmapArray, 0, length) 

bitmap.UnlockBits bitmapData 

//todo something with bitmapArray 

use stream = new MemoryStream(bitmapArray)           

let image = Bitmap.FromStream stream 

stream.Dispose |> ignore 

image 

任何想法,我究竟做錯了什麼?提前致謝。

+0

@ildjarn,哎,initialy bitmap.PixelFormat在那裏,我試圖使用特定的像素格式雖然排除故障,但得到了相同的異常 –

+0

順便說一句,你看到這個? http://stackoverflow.com/questions/5285213/parameter-is-not-valid-error-when-creating-image-from-byte-in-c-sharp –

+0

@FoggyFinder是的,我也試過,以及 –

回答

4

我不知道爲什麼你的代碼不工作(我測試它,並得到相同的結果)。

另一種選擇(爲我的作品),它是使用Marshal.UnsafeAddrOfPinnedArrayElement

let image = new Bitmap(width, height, bitmapData.Stride, bitmap.PixelFormat,Marshal.UnsafeAddrOfPinnedArrayElement(bi‌​tmapArray, 0)) 

編輯

感謝@ildjarn的解釋:

流沒有因爲它只是沒有任何的原始像素數據210圖像標題,因此無法知道諸如圖像 尺寸和調色板類型之類的簡單內容。流的方法是可行的,但你 需要將圖像保存頭到流,也不僅僅是 掃描線

+0

生成的位圖顯示正常。 –

+0

無論如何,我想知道爲什麼流在這種情況下不工作:( –

+3

@ d.dizhevskiy:流不工作,因爲它只是沒有任何圖像頭的原始像素數據,所以沒有辦法知道簡單比如圖像尺寸和調色板類型,可以使用流方式,但是您需要將圖像頭保存到流中,而不僅僅是掃描線。 – ildjarn