C#从System.Drawing.Bitmap高效地获取像素数据 [英] C# Getting the pixel data efficiently from System.Drawing.Bitmap

查看:1691
本文介绍了C#从System.Drawing.Bitmap高效地获取像素数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个硬盘(〜2GB)生24 bpp的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.

作为下一步我创建的新创建的数组的位图。结果
这是通过使用指针,所以没有涉及数据的复制完成。结果
接下来,我呼吁位图,它创建一个具有正确尺寸的新位图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[].

您不必删除已分配的字节数,你只需要它实现IDisposable完成后丢弃原Bitmap对象。

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高效地获取像素数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆