summaryrefslogtreecommitdiff
path: root/texturepng.cpp
blob: 19dd4abf150d22bf5a27bb637202640a99650a7d (plain)
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
#include <iostream>
#include <stdexcept>
#include <png.h>
#include "texturepng.h"

TexturePNG::TexturePNG(const char* filename) {
	FILE *file = fopen(filename, "rb");
	if(!file) {
		throw(std::runtime_error("TexturePNG file not found"));
	}
	png_byte header[8];
	fread(header, 1, 8, file);
	if(png_sig_cmp(header, 0, 8)) {
		throw(std::runtime_error("Invalid PNG file"));
	}
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
	if(!png_ptr) {
		throw(std::runtime_error("LibPNG Error (png_ptr)"));
	}
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if(!info_ptr) {
		throw(std::runtime_error("LibPNG Error (info_ptr)"));
	}
	png_infop end_info = png_create_info_struct(png_ptr);
	if(!end_info) {
		throw(std::runtime_error("LibPNG Error (end_info)"));
	}
	if (setjmp(png_jmpbuf(png_ptr))) {
		throw(std::runtime_error("LibPNG Error"));
	}
	png_init_io(png_ptr, file);
	png_set_sig_bytes(png_ptr, 8);
	png_read_png(png_ptr, info_ptr, 0, 0);
	png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
	width = png_get_image_width(png_ptr, info_ptr);
	height = png_get_image_height(png_ptr, info_ptr);
	data = new unsigned char[width * height * 4];
	for(int y = 0; y < height; y++) {
		for(int x = 0; x < width * 4; x++) {
			data[x + y*width*4] = row_pointers[y][x];
		}
	}
	build();
	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
}