問題描述
我在 HDD 上有幾個 (~2GB) 原始 24bpp RGB 文件.現在我想檢索它的一部分并將其縮放到所需的大小.
(唯一允許的比例是 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)
所以我目前正在將感興趣的矩形中的每一行讀取到一個數組中,這給我留下了一個高度正確但寬度錯誤的位圖.
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.
下一步,我將從新創建的數組中創建一個位圖.
這是通過使用指針完成的,因此不涉及數據復制.
接下來我在 Bitmap 上調用 GetThumbnailImage,它會創建一個具有正確尺寸的新位圖.
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.
現在我想返回新創建的位圖的原始像素數據(作為字節數組).但是為了實現這一點,我目前正在使用 LockBits 將數據復制到一個新數組中.
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.
所以我的問題是:有沒有辦法在不復制的情況下將像素數據從位圖中獲取到字節數組中?
類似于:
var bitmapData = scaledBitmap.LockBits(...)
byte[] rawBitmapData = (byte[])bitmapData.Scan0.ToPointer()
scaledBitmap.UnlockBits(bitmapData)
return rawBitmapData
我很清楚這行不通,這只是我想要實現的目標的一個例子.
I'm well aware that this doesn't work, it is just an example to what I basically want to achieve.
推薦答案
我認為這是您最好的選擇.
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);
如果你想傳遞一個字節[],你必須復制它.
You have to copy it, if you want a pass around a byte[].
您不必刪除已分配的字節,只需在完成后處理原始 Bitmap 對象,因為它實現了 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.
這篇關于C# 從 System.Drawing.Bitmap 高效獲取像素數據的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!