本文介绍了使用 unsafe 将透明度写入位图并保留原始颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我创建了透明位图,但将列表测试点中的像素着色为黄色.我怎样才能让它保持透明但像素要着色或保持它们的原始颜色而不是黄色?

In this code I'm creating Transparent bitmap but coloring the pixels in the List testpoints in yellow.How can I keep make it Transparent but the pixels to be coloring or keep with the original colors of them instead yellow ?

private void button2_Click(object sender, EventArgs e)
{
    Graphics g;
    g = Graphics.FromImage(bmpBackClouds);
    g.Clear(Color.Transparent);
    g.Dispose();
    BitmapData b1 = bmpBackClouds.LockBits(new System.Drawing.Rectangle(0, 0,
                    bmpBackClouds.Width, bmpBackClouds.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadWrite,
                    System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    int stride = b1.Stride;
    int i;

    System.IntPtr Scan0 = b1.Scan0;

    unsafe
    {
        byte* p;

        for (i = 0; i < testpoints.Count; i++)
        {
            p = (byte*)(void*)Scan0;

            p += (int)testpoints[i].Y * stride + (int)testpoints[i].X * 4;

            p[1] = p[2] = (byte)255;
            p[0] = (byte)0;
            p[3] = (byte)255;
        }
    }
    bmpBackClouds.UnlockBits(b1);
    bmpBackClouds.Save(@"c:\temp\yellowbmpcolor.png", ImageFormat.Png);
}

推荐答案

只要稍加修正,您的代码就可以正常工作:

You code will work fine with a tiny correction:

删除要删除图片的部分:

Delete the part where you delete the image:

Graphics g;
g = Graphics.FromImage(bmpBackClouds);
g.Clear(Color.Transparent);
g.Dispose();

这将清除图像,您最终将一无所有.

This will wipe out the image and you'll end up with nothing in it.

然后在改变这个之后

        p[1] = p[2] = (byte)255;
        p[0] = (byte)0;
        p[3] = (byte)255;

那个:

        p[3] = 0;

测试点列表中的部分将是透明的,它们的颜色通道完好无损.

the portions in your testpoints list will be transparent, with their color channels intact.

这有点难以看到;-)

最好的测试是读回它并恢复 alpha 通道,瞧,原始图像又回来了!

The best test is to read it back and to restore the alpha channel and voila, the original image is back!

注意 如果您想通过第一行使整个 Bitmap 透明 - 这不起作用.GDI 对透明度的处理有一个错误;大概是为了节省时间,当您尝试使用它使图像的一部分或全部透明时,它不会保留原始颜色.对于 Graphics.Clear 和其他 Graphics 方法(如 Graphics.FillRectangle 等)都是如此.

Note In case you wanted to make the whole Bitmap transparent by those first lines - This doesn't work. There is a bug in GDI's treatment of transparency; presumably to save time it doesn't preserve the original colors when you try to use it to make part of an image or all of it transparent. This it true both for Graphics.Clear and for the other Graphics methods like Graphics.FillRectangle etc..

..所以如果你想完全清除图像的 alpha 通道,使用上面的代码来完成,显然没有列表并且循环所有像素..

..so if you want to clear an image's alpha channel completely, use code like the above to do so, obviously without the list and with loops over all pixels..

这篇关于使用 unsafe 将透明度写入位图并保留原始颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:41
查看更多