From 73d7718c09ef23db851d0360ce726373f0bf7ac7 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Thu, 5 Nov 2015 21:45:31 +0000 Subject: Add JPEG support --- Makefile | 2 +- jpeg.c | 42 ++++++++++++++++++++++++++++++++++++++++++ loader.c | 3 +++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 jpeg.c diff --git a/Makefile b/Makefile index 7c23259..09dded0 100644 --- a/Makefile +++ b/Makefile @@ -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) diff --git a/jpeg.c b/jpeg.c new file mode 100644 index 0000000..5ec3b5f --- /dev/null +++ b/jpeg.c @@ -0,0 +1,42 @@ +#include +#include +#include +#include + +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; +} diff --git a/loader.c b/loader.c index 9f62d24..8d3015f 100644 --- a/loader.c +++ b/loader.c @@ -2,6 +2,7 @@ #include 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; -- cgit v1.2.3