問題描述
我在 HDD 上有幾個 (~2GB) 原始 24bpp RGB 文件.現(xiàn)在我想檢索它的一部分并將其縮放到所需的大小.
(唯一允許的比例是 1, 1/2, 1/4, 1/8, ..., 1/256)
I have several (~2GB) raw 24bpp RGB files on HDD.
Now I want to retrieve a portion of it and scale it to the desired size.
(The only scales allowed are 1, 1/2, 1/4, 1/8, ..., 1/256)
所以我目前正在將感興趣的矩形中的每一行讀取到一個數(shù)組中,這給我留下了一個高度正確但寬度錯誤的位圖.
So I'm currently reading every line from the rectangle of interest into an array, which leaves me with a bitmap which has correct height but wrong width.
下一步,我將從新創(chuàng)建的數(shù)組中創(chuàng)建一個位圖.
這是通過使用指針完成的,因此不涉及數(shù)據(jù)復(fù)制.
接下來我在 Bitmap 上調(diào)用 GetThumbnailImage,它會創(chuàng)建一個具有正確尺寸的新位圖.
As the next step I'm creating a Bitmap from the newly created array.
This is done with by using a pointer so there is no copying of data involved.
Next I'm calling GetThumbnailImage on the Bitmap, which creates a new bitmap with the correct dimensions.
現(xiàn)在我想返回新創(chuàng)建的位圖的原始像素數(shù)據(jù)(作為字節(jié)數(shù)組).但是為了實現(xiàn)這一點,我目前正在使用 LockBits 將數(shù)據(jù)復(fù)制到一個新數(shù)組中.
Now I want to return the raw pixel data (as a byte array) of the newly created bitmap. But to achieve that I'm currently copying the data using LockBits into a new array.
所以我的問題是:有沒有辦法在不復(fù)制的情況下將像素數(shù)據(jù)從位圖中獲取到字節(jié)數(shù)組中?
類似于:
var bitmapData = scaledBitmap.LockBits(...)
byte[] rawBitmapData = (byte[])bitmapData.Scan0.ToPointer()
scaledBitmap.UnlockBits(bitmapData)
return rawBitmapData
我很清楚這行不通,這只是我想要實現(xiàn)的目標(biāo)的一個例子.
I'm well aware that this doesn't work, it is just an example to what I basically want to achieve.
推薦答案
我認(rèn)為這是您最好的選擇.
I think this is your best bet.
var bitmapData = scaledBitmap.LockBits(...);
var length = bitmapData.Stride * bitmapData.Height;
byte[] bytes = new byte[length];
// Copy bitmap to byte[]
Marshal.Copy(bitmapData.Scan0, bytes, 0, length);
scaledBitmap.UnlockBits(bitmapData);
如果你想傳遞一個字節(jié)[],你必須復(fù)制它.
You have to copy it, if you want a pass around a byte[].
您不必刪除已分配的字節(jié),只需在完成后處理原始 Bitmap 對象,因為它實現(xiàn)了 IDisposable.
You don't have to delete the bytes that were allocated, you just need to Dispose of the original Bitmap object when done as it implements IDisposable.
這篇關(guān)于C# 從 System.Drawing.Bitmap 高效獲取像素數(shù)據(jù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!