diff options
author | Harry Jeffery <harry@exec64.co.uk> | 2015-11-05 21:45:31 +0000 |
---|---|---|
committer | Harry Jeffery <harry@exec64.co.uk> | 2015-11-05 21:45:31 +0000 |
commit | 73d7718c09ef23db851d0360ce726373f0bf7ac7 (patch) | |
tree | 7c474599d52d244707837e41959974ccbfcc9b0a | |
parent | b8976522a76ec76affce76d785f74b0ba3fda332 (diff) | |
download | imv-73d7718c09ef23db851d0360ce726373f0bf7ac7.tar.gz |
Add JPEG support
-rw-r--r-- | Makefile | 2 | ||||
-rw-r--r-- | jpeg.c | 42 | ||||
-rw-r--r-- | loader.c | 3 |
3 files changed, 46 insertions, 1 deletions
@@ -1,7 +1,7 @@ .PHONY: clean CFLAGS = -g -W -Wall -std=c11 `sdl2-config --cflags` -LDFLAGS = `sdl2-config --libs` -lpng +LDFLAGS = `sdl2-config --libs` -lpng -ljpeg TARGET = imv SOURCES = $(wildcard *.c) @@ -0,0 +1,42 @@ +#include <SDL2/SDL.h> +#include <string.h> +#include <jpeglib.h> +#include <setjmp.h> + +SDL_Texture* imv_load_jpeg(SDL_Renderer *r, const char* path) +{ + FILE *fp = fopen(path, "rb"); + if(!fp) { + return NULL; + } + + struct jpeg_decompress_struct cinfo; + jpeg_create_decompress(&cinfo); + struct jpeg_error_mgr jerr; + cinfo.err = jpeg_std_error(&jerr); + + jpeg_stdio_src(&cinfo, fp); + jpeg_read_header(&cinfo, TRUE); + jpeg_start_decompress(&cinfo); + int row_stride = cinfo.output_width * cinfo.output_components; + JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) + ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); + char* pixels = (char*)malloc(row_stride*cinfo.output_height); + while (cinfo.output_scanline < cinfo.output_height) { + jpeg_read_scanlines(&cinfo, buffer, 1); + void *out_row = pixels + row_stride * (cinfo.output_scanline-1); + memcpy(out_row, buffer[0], row_stride); + } + jpeg_finish_decompress(&cinfo); + jpeg_destroy_decompress(&cinfo); + fclose(fp); + + SDL_Texture *img = SDL_CreateTexture(r, + SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STATIC, + cinfo.output_width, cinfo.output_height); + + SDL_Rect area = {0,0,cinfo.output_width,cinfo.output_height}; + SDL_UpdateTexture(img, &area, pixels, row_stride); + free(pixels); + return img; +} @@ -2,6 +2,7 @@ #include <string.h> extern SDL_Texture* imv_load_png(SDL_Renderer *r, const char* path); +extern SDL_Texture* imv_load_jpeg(SDL_Renderer *r, const char* path); SDL_Texture* imv_load_image(SDL_Renderer *r, const char* path) { @@ -27,6 +28,8 @@ SDL_Texture* imv_load_image(SDL_Renderer *r, const char* path) return img; } else if(strcasecmp(ext, ".png") == 0) { return imv_load_png(r, path); + } else if(strcasecmp(ext, ".jpeg") == 0 || strcasecmp(ext, ".jpg") == 0) { + return imv_load_jpeg(r, path); } return NULL; |