欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Bitmap 复制的小例子

程序员文章站 2024-02-20 15:11:46
复制代码 代码如下:public bitmap copybitmap(bitmap source){    int depth = bitma...

复制代码 代码如下:

public bitmap copybitmap(bitmap source)
{
    int depth = bitmap.getpixelformatsize(source.pixelformat);

    if (depth != 8 && depth != 24 && depth != 32)
    {
        return null;
    }

    bitmap destination = new bitmap(source.width, source.height, source.pixelformat);

    bitmapdata source_bitmapdata = null;
    bitmapdata destination_bitmapdata = null;

    try
    {
        source_bitmapdata = source.lockbits(new rectangle(0, 0, source.width, source.height), imagelockmode.readwrite,
                                        source.pixelformat);
        destination_bitmapdata = destination.lockbits(new rectangle(0, 0, destination.width, destination.height), imagelockmode.readwrite,
                                        destination.pixelformat);

        unsafe
        {
            byte* source_ptr = (byte*)source_bitmapdata.scan0;
            byte* destination_ptr = (byte*)destination_bitmapdata.scan0;

            for (int i = 0; i < (source.width * source.height * (depth / 8)); i++)
            {
                *destination_ptr = *source_ptr;
                source_ptr++;
                destination_ptr++;
            }
        }

        source.unlockbits(source_bitmapdata);
        destination.unlockbits(destination_bitmapdata);

        return destination;
    }
    catch
    {
        destination.dispose();
        return null;
    }
}