Generate RGBA Portable Graphic Image in C++

In this tutorial, we will learn how to generate an RGBA portable graphic image in C++.

RGBA stands for Red, Green, Blue, Alpha. It is three passage RGB color model and the fourth passage is alpha.

Alpha means how opaque each pixel is.

PNG images support many properties such as transparency in the images, multiple colors, gamma correction(it determines how bright the output of display), lossless compression(reduce the size of the file without losing the quality of the photo), etc.

for working with a png file, it uses the PNGwiter platform. PNGwriter is a very easy-to-use open-source graphics library that uses PNG as its output format.

It supports plotting and reading pixels in the RGB (red, green, blue), HSV (hue, saturation, value/brightness), and CMYK (cyan, magenta, yellow, black) color spaces.

How an image is generated:

The smallest unit for generating an image is a pixel.

Each pixel has a numeric value that represents a color.

These are the following steps for generating an image.

1. We need to define the height and width of an image.

2. Iterate and apply pixel by pixel, then stores the collection of pixel with proper extension and properties.

#include <iostream> 
#include <pngwriter.h> 
#include <string> 
using namespace std;  
void generate(int const width, 
                  int const height, string FilePath) 
     cout<< "FilePath: " << FilePath.c_str(); //print filepath
    pngwriter flag{ width, height, 0, };  // Generate the flag 
    // Calculate size
    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 
int main() 
    int w = 300, h = 500; 
    string f; 
    generate(w, h, f); 
    return 0; 
Output:It will give three passage of rgb.

Next Topic:

Code Bloating in C++ with Examples

Leave a Reply

Your email address will not be published. Required fields are marked *