通过C ++生成RGBA图像

Home / C++ MrLee 2020-6-4 2852

PNG图像能够支持多种图像属性,例如多种颜色,透明度,伽玛校正,无损压缩等。PNG图像被广泛使用,并且是多种类型图像的首选。

为了处理PNG文件,我们将使用PNGwriter平台无关的包装开源C ++库,用于libpng(PNG参考库),这是功能最丰富的库之一,用C编写PNGwriter库可在Linux,Unix,macOS和Windows上运行。其受支持的功能包括打开现有的PNG图像,在RGB,HSV和CMYK颜色空间中绘制和读取像素,基本形状,缩放,双线性插值,完整的TrueType抗锯齿和旋转文本支持以及Bezier曲线。它需要FreeType2库来支持文本。
有关更多文档和库,请访问SourceForgePNGwriter-github

如何生成图像:
像素是共同生成图像的最小单位。每个像素都有一些代表颜色的数值。步骤如下:

  1. 我们选择所需的图像高度和宽度。
  2. 根据需要,我们逐像素迭代并应用颜色。
  3. 然后以适当的扩展名和属性存储此像素集合,从而生成图像。

通过应用颜色生成图像:

源码

// C++ program to generate PNG images 
#include <iostream> 
#include <pngwriter.h> 
#include <string> 
// Function to generate PNG image 
void generate_PNG(int const width, 
				int const height, 
				std::string filepath) 
{ 
	// Print the filepath 
	cout << endl 
		<< "Filepath: "
		<< filepath.c_str(); 
	// Generate the flag 
	pngwriter flag{ width, height, 0, 
					filepath.data() }; 
	// Calculate sizes 
	int const size = width / 3; 
	// Fill the squares 
	flag.filledsquare(0, 0, size, 
					2 * size, 0, 
					0, 65535); 
	flag.filledsquare(size, 0, 2 * size, 
					2 * size, 0, 
					65535, 65535); 
	flag.filledsquare(2 * size, 0, 
					3 * size, 2 * size, 
					65535, 0, 65535); 
	// Close the flag 
	flag.close(); 
} 
// Driver code 
int main() 
{ 
	// Given width and height 
	int width = 300, height = 200; 
	// Filepath 
	std::string filepath; 
	// Function call to generate PNG image 
	generate_PNG(width, height, filepath); 
	return 0; 
}

输出:

说明:
上面的程序采用文件名的宽度,高度和文件地址。pngwriter类表示PNG图像。PNG图像的构造函数允许我们设置像素的宽度和高度,背景色以及应保存图像的文件的路径。如上面的代码所示,我们只是并排排列了三种纯色,为此,我们使用了fillsquare()函数,该函数从开始位置到结束位置都获取了xy坐标值和一个颜色值(R,G,B )当映像保存在内存中时,然后调用close()方法将其保存到磁盘文件中。


本文链接:https://www.it72.com/12640.htm

推荐阅读
最新回复 (0)
返回