NOTE: This post has moved to https://blog.gibson.sh/2015/03/23/comparing-performance-stb_image-vs-libjpeg-turbo-libpng-and-lodepng/
The original article is kept here for now, but is not maintained in any way.
I recently tried out Sean Barrett’s stb_image and was blown away by how fucking easy it is to use.
Integrating it into your project is trivial: Just add the header and somewhere do:
#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
That’s all. (If you wanna use it in multiple files you just #include "stb_image.h"
there without the #define.)
And the API is trivial too:
int width, height, bytesPerPixel; unsigned char* pixeldata = stbi_load("bla.jpg", &width, &height, &bytesPerPixel, 0); // if you have already read the image file data into a buffer: unsigned char* pixeldata2 = stbi_load_from_memory(bufferWithImageData, bufferLength, &width, &height, &bytesPerPixel, 0); if(pixeldata2 == NULL) printf("Some error happened: %sn", stbi_failure_reason());
There’s also a simple callback-API which allows you to define some callbacks that stb_image will call to get the data, handy if you’re using some kind of virtual filesystem or want to load the data from .zip files or something.
And it supports lots of common image file types including JPEG, PNG, TGA, BMP, GIF and PSD.
So I wondered if there are any downsides regarding speed.
In short: (On my machine) it’s faster than libjpeg, a bit slower than libjpeg-turbo, twice as fast as lodepng (another one-file-png decoder which also has a nice API) and a bit slower than libpng. For smaller images stb_image’s performance is even closer to libpng/libjpeg-turbo. GCC produces faster code than Clang. All in all I find the performance acceptable and will use stb_image more in the future (my first “victim” was Yamagi Quake II).
The average times decoding a 4000x3000pixel image in milliseconds for GCC and clang with different optimization levels:
(more…)