Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <png.h>
- #include <stdio.h>
- typedef struct
- {
- unsigned char* Data;
- unsigned int Width, Height;
- enum { RGB, RGBA } Type;
- } Image;
- BOOL LoadPng(char const* fileName, Image* image)
- {
- FILE *fp = fopen(fileName, "rb");
- unsigned char header[8];
- if(fread(header, 1, 8, fp) != 8 || png_sig_cmp(header, 0, 8) != 0)
- {
- fclose(fp);
- return FALSE;
- }
- png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- if(!png == NULL)
- {
- fclose(fp);
- return FALSE;
- }
- png_infop info = png_create_info_struct(png);
- if(info == NULL)
- {
- fclose(fp);
- png_destroy_read_struct(&png, NULL, NULL);
- return FALSE;
- }
- if(setjmp(png_jmpbuf(png)))
- {
- if(image->Data != NULL);
- {
- free(image->Data);
- }
- fclose(fp);
- png_destroy_read_struct(&png, &info, NULL);
- return FALSE;
- }
- png_init_io(png, fp);
- png_set_sig_bytes(png, 8); // Already read the first 8 bytes.
- png_read_png(png, info, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);
- image->Width = png_get_image_width(png, info);
- image->Height = png_get_image_height(png, info);
- image->Type = png_get_color_type(png, info) == PNG_COLOR_TYPE_RGB ? RGB : RGBA;
- png_size_t stride = png_get_rowbytes(png, info);
- image->Data = malloc(stride * image->Height); // stride rather than width to take into account padding
- // Flipping the rows because OpenGL uses bottom left as origin
- png_bytepp rows = png_get_rows(png, info);
- for(unsigned int i = 0; i < image->Height; i++)
- {
- memcpy(image->Data + (stride * i), rows[image->Height - 1 - i], stride);
- }
- png_destroy_read_struct(&png, &info, NULL);
- fclose(fp);
- return TRUE;
- }
Advertisement
Add Comment
Please, Sign In to add comment