C++ Paste by a1337q
Description: write red png
Hide line numbers

Create new paste
Post a reply
View replies

Paste:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
#include <png.h>
#include <stdio.h>
#include <stdlib.h>

// return codes:
// 0 - normal
// 1 - fopen error
// 2 - png struct initializing error
// 3 - init_io error
// 4 - error writing header
// 5 - error writing bytes
// 6 - error writing end

int main() {
  // ------------------------
  // initialize all variables
  // ------------------------
  unsigned width = 1003;
  unsigned height = 500;

  // don't know why we need all these:
  png_byte  bit_depth = '\b';
  png_byte color_type = '\006';
  int rowbytes = 4000;
  png_bytep* row_pointers;

  // initializing the row_pointers:
  row_pointers = (png_bytep *) malloc (sizeof (png_bytep) * height);
  for(unsigned y = 0; y < height; ++y)
    row_pointers[y] = (png_byte *) malloc (rowbytes);

  // fill all black
  png_byte* row;
  png_byte* ptr;
  for(unsigned y=0; y < height; ++y) {
    for(unsigned x=0; x < width; ++x) {
      row = row_pointers[y];
      ptr = &(row[x * 4]);
      ptr[0] = 255;   // red
      ptr[1] = 0;     // green
      ptr[2] = 0;     // blue
      ptr[3] = 127;   // alpha
    }
  }
  // ---------------
  // writing the png
  // ---------------

  // these 2 are needed for writing
  png_structp png_ptr;
  png_infop info_ptr;

  FILE* fp = fopen("500x500.png", "wb");
  if(!fp)
    return 1;

  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

  if(!png_ptr)
    return 2;

  info_ptr = png_create_info_struct(png_ptr);

  if(!info_ptr)
    return 2;

  if(setjmp(png_jmpbuf(png_ptr)))
    return 3;

  png_init_io(png_ptr, fp);

  // write header
  if(setjmp(png_jmpbuf(png_ptr)))
    return 4;

  png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  png_write_info(png_ptr, info_ptr);

  // write bytes
  if(setjmp(png_jmpbuf(png_ptr)))
    return 5;

  png_write_image(png_ptr, row_pointers);

  // write end
  if(setjmp(png_jmpbuf(png_ptr)))
    return 6;

  png_write_end(png_ptr, NULL);

  // -------
  // cleanup
  // -------
  for(unsigned y=0; y < height; ++y)
    free(row_pointers[y]);
  free(row_pointers);

  fclose(fp);

  return 0;
}

Replies:
Reply by a1337q
compiles with
$ g++ -lpng whatever.cpp

Reply by mxbydZSvQxypwRC
I am forever inebdted to you for this information.

    (some replies deleted)