aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHarry Jeffery <harry@exec64.co.uk>2015-11-05 21:45:31 +0000
committerHarry Jeffery <harry@exec64.co.uk>2015-11-05 21:45:31 +0000
commit73d7718c09ef23db851d0360ce726373f0bf7ac7 (patch)
tree7c474599d52d244707837e41959974ccbfcc9b0a
parentb8976522a76ec76affce76d785f74b0ba3fda332 (diff)
downloadimv-73d7718c09ef23db851d0360ce726373f0bf7ac7.tar.gz
Add JPEG support
-rw-r--r--Makefile2
-rw-r--r--jpeg.c42
-rw-r--r--loader.c3
3 files changed, 46 insertions, 1 deletions
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 <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;
+}
diff --git a/loader.c b/loader.c
index 9f62d24..8d3015f 100644
--- a/loader.c
+++ b/loader.c
@@ -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;