CSharpGL(19)用glReadPixels把渲染的内容保存为PNG图片(C#)
本文解决了将OpenGL渲染出来的内容保存到PNG图片的方法。
下载
CSharpGL已在GitHub开源,欢迎对OpenGL有兴趣的同学加入(https://github.com/bitzhuwei/CSharpGL)
glReadPixels
C#里声明glReadPixels的形式如下:
1 /// <summary> 2 /// Reads a block of pixels from the frame buffer. 3 /// </summary> 4 /// <param name="x">Top-Left X value.</param> 5 /// <param name="y">Top-Left Y value.</param> 6 /// <param name="width">Width of block to read.</param> 7 /// <param name="height">Height of block to read.</param> 8 /// <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> 9 /// <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> 10 /// <param name="pixels">Storage for the pixel data received.</param> 11 [DllImport(Win32.OpenGL32, EntryPoint = "glReadPixels", SetLastError = true)] 12 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窗口是以左上角为原点的。所以用的时候要注意转换一下。
数据结构
为方便起见,我先定义一个描述像素的数据结构。
1 struct Pixel 2 { 3 public byte r; 4 public byte g; 5 public byte b; 6 public byte a; 7 8 public Pixel(byte r, byte g, byte b, byte a) 9 { 10 this.r = r; this.g = g; this.b = b; this.a = a; 11 } 12 13 public Color ToColor() 14 { 15 return Color.FromArgb(a, r, g, b); 16 } 17 18 public override string ToString() 19 { 20 return string.Format("{0}, {1}, {2}, {3}", r, g, b, a); 21 } 22 }