Skip to content

Instantly share code, notes, and snippets.

@shuxiao9058
Created August 27, 2014 15:38
Show Gist options
  • Save shuxiao9058/d0aac359a33c8f2f87e4 to your computer and use it in GitHub Desktop.
Save shuxiao9058/d0aac359a33c8f2f87e4 to your computer and use it in GitHub Desktop.
save jpg file with libjpeg-tubo
#include <string.h>
#include <stdio.h>
#include "libjpeg-turbo/turbojpeg.h"
#pragma comment(lib, "turbojpeg.lib")
bool savejpg(const char* filename,const unsigned char* pData,int width,int height, int nchannels);
int main(int argc, char **argv)
{
int width = 352, height = 288;
unsigned char *img_data = new unsigned char[width * height * 4];
memset(img_data, 0, width * height * 4);
savejpg("a.jpg", img_data, width, height, 4);
}
bool savejpg(const char* filename,const unsigned char* pData,int width,int height, int nchannels)
{
const int JPEG_QUALITY = 100;
const int COLOR_COMPONENTS = nchannels;
long unsigned int size = 0;
unsigned char* output = nullptr;
unsigned char *buffer = new unsigned char[width*height*nchannels];
memcpy(buffer, pData, width*height*nchannels);
tjhandle handleCompress = tjInitCompress();
tjCompress2(handleCompress, buffer, width, 0, height, TJPF_BGRA, // 注意这里可以直接压缩rgba数据
&output, &size, TJSAMP_444, JPEG_QUALITY,
TJFLAG_FASTDCT);
FILE * file = fopen(filename, "wb");
if (!file) {
fprintf(stderr, "open file %s failed!\n", filename);
delete buffer;
return false;
}
fwrite (output, 1, size, file);
fclose(file);
tjDestroy(handleCompress);
tjFree(output);
delete buffer;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment