Bitmap.Lockbits混乱 [英] Bitmap.Lockbits confusion

查看:489
本文介绍了Bitmap.Lockbits混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN参考:[1] http://msdn.microsoft.com/en-us /library/5ey6h79d.aspx#Y1178

MSDN reference: [1] http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx#Y1178

从链接它说,第一个参数将指定位图的部分锁定,我设置是位图的一小部分(位图是500×500,我的矩形是(0,0,50,50)),然而,返回的BitmapData具有1500(= 500×3),以便基本上每个扫描将仍然在整个扫描步幅水平图片。不过,我要的是位图的只有左上角50×50的一部分。

From the link it says that the first argument will "specifies the portion of the Bitmap to lock" which I set to be a smaller part of the Bitmap (Bitmap is 500x500, my rectangle is (0,0,50,50)) however the returned BitmapData has stride of 1500 (=500*3) so basically every scan will still scan through the whole picture horizontally. However, what I want is only the top left 50x50 part of the bitmap.

这是如何工作的?

推荐答案

的步幅将始终是充分的位图的,但是SCAN0属性将根据锁定矩形的始点,以及这两个BitmapData的高度和宽度是不同的。

The stride will always be of the full bitmap, but the Scan0 property will be different according to the start point of the lock rectangle, as well as the Height and Width of the BitmapData.

这其中的原因是,你仍然需要知道的位图的实际位宽,为了遍历行(增加步幅来解决)。

The reason for that is that you will still need to know the real bit-width of the bitmap, in order to iterate over the rows (add stride to address).

一个简单的方式去了解这将是:

A simple way to go about it would be:

var bitmap = new Bitmap(100, 100);

var data = bitmap.LockBits(new Rectangle(0, 0, 10, 10),
                           ImageLockMode.ReadWrite,
                           bitmap.PixelFormat);

var pt = (byte*)data.Scan0;
var bpp = data.Stride / bitmap.Width;

for (var y = 0; y < data.Height; y++)
{
    // This is why real scan-width is important to have!
    var row = pt + (y * data.Stride);

    for (var x = 0; x < data.Width; x++)
    {
        var pixel = row + x * bpp;

        for (var bit = 0; bit < bpp; bit++)
        {
            var pixelComponent = pixel[bit];
        }
    }
}

bitmap.UnlockBits(data);



因此​​,它基本上是真的只是锁定整个位图,但给你一个指向左上角位图中的矩形,并设置扫描的宽度和高度适当的像素

So it is basically really just locking the whole bitmap, but giving you a pointer to the top-left pixel of the rectangle in the bitmap, and setting the scan's width and height appropriately.

这篇关于Bitmap.Lockbits混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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