Created
October 27, 2020 11:46
-
-
Save harieamjari/9ed32970f9a11ad2340d747b5cefcc18 to your computer and use it in GitHub Desktop.
Writing libpng template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <png.h> | |
int width, height; | |
int main(){ | |
width = 1500; height = 1000; | |
char filename[] = "t.png"; | |
/*open stream */ | |
FILE *fp = fopen(filename, "wb"); | |
if (fp==NULL){ | |
perror(filename); | |
exit(1); | |
} | |
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); | |
if (!png) {fprintf(stderr, "png_structp_png at line %d: failed\n", __LINE__); return 1;} | |
png_infop info = png_create_info_struct(png); | |
if (!info) {fprintf(stderr, "png_infop at line %d: failed\n", __LINE__); return 1;} | |
if (setjmp(png_jmpbuf(png))) {fprintf(stderr, "setjump at line %d: abort\n", __LINE__); return 1;} | |
png_init_io(png, fp); | |
png_set_IHDR( | |
png, | |
info, | |
width, height, | |
8, | |
PNG_COLOR_TYPE_RGBA, | |
PNG_INTERLACE_NONE, | |
PNG_COMPRESSION_TYPE_DEFAULT, | |
PNG_FILTER_TYPE_DEFAULT); | |
png_write_info(png, info); | |
png_bytep *row = NULL; | |
row = (png_bytep*) malloc(sizeof(png_bytep)*height); | |
if (row == NULL) {fprintf(stderr, "malloc at line %d: failed\n", __LINE__); return 1;} | |
for (int y = 0; y < height; y++) { | |
row[y] = malloc(sizeof(png_bytep)*width); | |
if (row[y] == NULL) {fprintf(stderr, "allocating row failed: memory leak occured!! \n");return 1;} | |
png_bytep line = row[y]; | |
png_byte val0 = 0x00; | |
for (int x = 0; x < width; x++){ | |
png_bytep px = (line+(x*4)); | |
px[0] =val0;val0++;val0%=0xFF; | |
px[1] = px[0]; | |
px[2] = px[0] | |
px[3] = 0xFF; | |
} | |
} | |
png_write_image(png, row); | |
png_write_end(png, NULL); | |
for (int y = 0; y < height; y++) free(row[y]); | |
free(row); | |
fclose(fp); | |
png_destroy_write_struct(&png, &info); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment