CSharpGL(19)用glReadPixels把渲染的内容保存为PNG图片(C#)

效果图

本文解决了将OpenGL渲染出来的内容保存到PNG图片的方法。

CSharpGL(19)用glReadPixels把渲染的内容保存为PNG图片(C#)-LMLPHP

CSharpGL(19)用glReadPixels把渲染的内容保存为PNG图片(C#)-LMLPHP

下载

CSharpGL已在GitHub开源,欢迎对OpenGL有兴趣的同学加入(https://github.com/bitzhuwei/CSharpGL

glReadPixels

C#里声明glReadPixels的形式如下:

         /// <summary>
/// Reads a block of pixels from the frame buffer.
/// </summary>
/// <param name="x">Top-Left X value.</param>
/// <param name="y">Top-Left Y value.</param>
/// <param name="width">Width of block to read.</param>
/// <param name="height">Height of block to read.</param>
/// <param name="format">Specifies the format of the pixel data. The following symbolic values are accepted: OpenGL.COLOR_INDEX, OpenGL.STENCIL_INDEX, OpenGL.DEPTH_COMPONENT, OpenGL.RED, OpenGL.GREEN, OpenGL.BLUE, OpenGL.ALPHA, OpenGL.RGB, OpenGL.RGBA, OpenGL.LUMINANCE and OpenGL.LUMINANCE_ALPHA.</param>
/// <param name="type">Specifies the data type of the pixel data.Must be one of OpenGL.UNSIGNED_BYTE, OpenGL.BYTE, OpenGL.BITMAP, OpenGL.UNSIGNED_SHORT, OpenGL.SHORT, OpenGL.UNSIGNED_INT, OpenGL.INT or OpenGL.FLOAT.</param>
/// <param name="pixels">Storage for the pixel data received.</param>
[DllImport(Win32.OpenGL32, EntryPoint = "glReadPixels", SetLastError = true)]
public static extern void ReadPixels(int x, int y, int width, int height, uint format, uint type, IntPtr pixels);

这个函数的功能是:将指定范围(x, y, width, height)的像素值读入指定的内存处(pixels)。能把像素信息读到内存里,就可以保存到文件了。

其中(x, y)是以窗口左下角为原点(0, 0)的。而Windows窗口是以左上角为原点的。所以用的时候要注意转换一下。

数据结构

为方便起见,我先定义一个描述像素的数据结构。

     struct Pixel
{
public byte r;
public byte g;
public byte b;
public byte a; public Pixel(byte r, byte g, byte b, byte a)
{
this.r = r; this.g = g; this.b = b; this.a = a;
} public Color ToColor()
{
return Color.FromArgb(a, r, g, b);
} public override string ToString()
{
return string.Format("{0}, {1}, {2}, {3}", r, g, b, a);
}
}

struct Pixel

为了使用非托管数组,还需要用到 UnmanagedArray<T> 。关于这个类型详情见(C#+无unsafe的非托管大数组(large unmanaged array in c# without 'unsafe' keyword))。

方法一:Bitmap.SetPixel()

最直接的方法是用Bitmap.SetPixel()来一个一个地指定图片的像素值。

         /// <summary>
/// 把OpenGL渲染的内容保存到图片文件。
/// </summary>
/// <param name="x">左下角坐标为(0, 0)</param>
/// <param name="y">左下角坐标为(0, 0)</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename"></param>
public static void Save2Picture(int x, int y, int width, int height, string filename)
{
var pdata = new UnmanagedArray<Pixel>(width * height);
GL.ReadPixels(x, y, width, height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pdata.Header);
var bitmap = new Bitmap(width, height);
int index = ;
for (int j = height - ; j >= ; j--)
{
for (int i = ; i < width; i++)
{
Pixel v = pdata[index++];
Color c = v.ToColor();
bitmap.SetPixel(i, j, c);
}
} bitmap.Save(filename);
}

方法二:Marshal.Copy

方法一用到的SetPixel()速度是很慢的。

先把读到的内容写入一个byte[],然后再用Marshal.Copy()复制到Bitmap。这个方法的思路是(非托管数组->托管数组->bmpData.Scan0)

         /// <summary>
/// 把OpenGL渲染的内容保存到图片文件。
/// </summary>
/// <param name="x">左下角坐标为(0, 0)</param>
/// <param name="y">左下角坐标为(0, 0)</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename"></param>
public static void Save2Picture(int x, int y, int width, int height, string filename)
{
var pdata = new UnmanagedArray<Pixel>(width * height);
GL.ReadPixels(x, y, width, height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pdata.Header);
var format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
var lockMode = System.Drawing.Imaging.ImageLockMode.WriteOnly;
var bitmap = new Bitmap(width, height, format);
var bitmapRect = new Rectangle(, , bitmap.Width, bitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(bitmapRect, lockMode, format);
{
int length = Math.Abs(bmpData.Stride) * bitmap.Height;
byte[] bitmapBytes = new byte[length];
int index = ;
for (int j = height - ; j >= ; j--)
{
for (int i = ; i < width; i++)
{
Pixel v = pdata[index++];
bitmapBytes[j * bmpData.Stride + i * + ] = v.b;
bitmapBytes[j * bmpData.Stride + i * + ] = v.g;
bitmapBytes[j * bmpData.Stride + i * + ] = v.r;
bitmapBytes[j * bmpData.Stride + i * + ] = v.a;
}
} System.Runtime.InteropServices.Marshal.Copy(bitmapBytes, , bmpData.Scan0, length);
}
bitmap.UnlockBits(bmpData); bitmap.Save(filename);
}

方法三:直接写入bmpData.Scan0

上一个方法里,通过托管数组byte[]进行过渡,是为了使用Marshal.Copy()这个method。但是我明明可以直接操作bmpData.Scan0啊,何必弄个byte[]。

         /// <summary>
/// 把OpenGL渲染的内容保存到图片文件。
/// </summary>
/// <param name="x">左下角坐标为(0, 0)</param>
/// <param name="y">左下角坐标为(0, 0)</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename"></param>
public static void Save2Picture(int x, int y, int width, int height, string filename)
{
var pdata = new UnmanagedArray<Pixel>(width * height);
GL.ReadPixels(x, y, width, height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pdata.Header);
var format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
var lockMode = System.Drawing.Imaging.ImageLockMode.WriteOnly;
var bitmap = new Bitmap(width, height, format);
Rectangle bitmapRect = new Rectangle(, , bitmap.Width, bitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(bitmapRect, lockMode, format);
unsafe
{
var array = (byte*)bmpData.Scan0.ToPointer();
int index = ;
for (int j = height - ; j >= ; j--)
{
for (int i = ; i < width; i++)
{
Pixel v = pdata[index++];
array[j * bmpData.Stride + i * + ] = v.b;
array[j * bmpData.Stride + i * + ] = v.g;
array[j * bmpData.Stride + i * + ] = v.r;
array[j * bmpData.Stride + i * + ] = v.a;
}
}
}
bitmap.UnlockBits(bmpData); bitmap.Save(filename);
}

方法四:ReadPixels直接搞定

在上面的方法里,思路是(非托管数组->非托管数组)。

显然这个转换步骤也是多余的,直接让ReadPixels写入bmpData.Scan0的位置不就好了嘛。

         /// <summary>
/// 把OpenGL渲染的内容保存到图片文件。
/// </summary>
/// <param name="x">左下角坐标为(0, 0)</param>
/// <param name="y">左下角坐标为(0, 0)</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename"></param>
public static void Save2Picture(int x, int y, int width, int height, string filename)
{
var format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
var lockMode = System.Drawing.Imaging.ImageLockMode.WriteOnly;
var bitmap = new Bitmap(width, height, format);
var bitmapRect = new Rectangle(, , bitmap.Width, bitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(bitmapRect, lockMode, format);
GL.ReadPixels(x, y, width, height, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, bmpData.Scan0);
bitmap.UnlockBits(bmpData);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); bitmap.Save(filename);
}

总结

从OpenGL窗口读取出图片,是非常有用的。

原CSharpGL的其他功能(UI、3ds解析器、TTF2Bmp、CSSL等),我将逐步加入新CSharpGL。

欢迎对OpenGL有兴趣的同学关注(https://github.com/bitzhuwei/CSharpGL

04-26 05:49