处理1bpp图像 [英] Working with 1bpp images

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

问题描述

我需要执行1bpp图像的关键性能"操作. 实际上,我正在使用Bitmap类,并且正在执行图形更新周期的每次迭代,即在字节数组中复制位图.

I have a "performance critical" operation where I need to work with 1bpp images. Actually I'm using the Bitmap class and I'm doing, each iteration of a graphic update cycle, a copy of the bitmap inside the byte array.

看着我的任务管理器,这不是我能继续做的事情:它始终使用2%的cpu,我认为对于诸如实用程序之类的东西来说,这很多.

Watching my task manager, this is not that I can keep doing: it uses 2% cpu all time, I think it's quite a lot for something like an utility program.

我需要尽可能少地浪费内存,几乎要消耗0 cpu.图片为160x43,非常小.

I need to waste less memory as possible and almost 0 cpu. The image is 160x43, quite small.

为什么我不直接使用字节数组?简单:我想重写它,做一些我不想自己重写的常见操作.

Why I am not using directly the byte array? Easy: I would like to write over it, do some common operations which I don't want to rewrite by myself.

我可以明显使用其他图像类(例如,从wpf,我不知道).我需要处理1bpp的图像.

I can use obviusly a different image class (from wpf for example, I don't know). I need the possibility to work with a 1bpp image.

主题: 对于32bpp图像,我有相同的问题",我需要一种将其作为图像处理的方式,尽管它是字节数组,但我不能每次都复制字节!!!我这样浪费CPU.

Offtopic: I have the same "problem" with a 32bpp image, I need a way to work with it as an image while it is a byte array, I can't make a copy of my bytes each time!!! I'm wasting cpu in this way.

推荐答案

您应使用 Bitmap.LockBits 获取固定的位图的底层内存(这样友好的垃圾回收器不会为您移动它).

You should use Bitmap.LockBits to get the underlying memory of the bitmap pinned (so the friendly garbage collector won't move it around for you).

作为示例,这个小程序加载png,设置简单的像素模式并保存生成的图像:

As an example, this small program loads a png, sets a simple pixel pattern, and saves the resulting image:

unsafe void Main()
{
    Bitmap bm = (Bitmap)Image.FromFile("D:\\word.png");
    var locked = bm.LockBits(new Rectangle(0,0,bm.Width, bm.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
    try 
    {
        byte v = 0xaa;
        byte* pBuffer = (byte*)locked.Scan0;
        for(int r = 0 ; r < locked.Height ; r++) 
        {
            byte* row = pBuffer + r*locked.Stride;
            for(int c = 0 ; c < locked.Stride ; c++) 
                row[c] = v;
        }
    }
    finally
    {
        bm.UnlockBits(locked);
    }
    bm.Save("D:\\generated.png");
}

LockBits将产生开销,具体取决于是否需要将内部存储器表示形式转换为您所请求的内容(因此,从何处获取它可能很重要).作为具有绩效的女企业家,可以通过测量和剖析来找到您的瓶颈.

LockBits will have an overhead depending on whether it needs to convert the internal memory representation to what you request (so it might matter where you get it from). As alwyas with performance, measure and profile to find your bottlenecks.

这篇关于处理1bpp图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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