JPEG解压为RGB
int tj3_decode_image(const char* jpeg_file)
{
tjscalingfactor scalingFactor = TJUNSCALED;
int outSubsamp = -1, outQual = -1;
int width, height;
FILE* jpegFile = NULL;
unsigned char* imgBuf = NULL, * jpegBuf = NULL;
int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
tjhandle tjInstance = NULL;
int fastUpsample = 1, fastDCT = 1;
long size;
int inSubsamp, inColorspace;
size_t jpegSize;
if ((tjInstance = tj3Init(TJINIT_DECOMPRESS)) == NULL)
THROW_TJ("creating TurboJPEG instance");
if ((jpegFile = fopen(jpeg_file, "rb")) == NULL)
THROW_UNIX("opening input file");
if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
fseek(jpegFile, 0, SEEK_SET) < 0)
THROW_UNIX("determining input file size");
if (size == 0)
THROW("determining input file size", "Input file contains no data");
jpegSize = size;
if ((jpegBuf = (unsigned char*)tj3Alloc(jpegSize)) == NULL)
THROW_UNIX("allocating JPEG buffer");
if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
THROW_UNIX("reading input file");
fclose(jpegFile); jpegFile = NULL;
printf("jpegSize:%d\n", jpegSize);
if (tj3Set(tjInstance, TJPARAM_FASTUPSAMPLE, fastUpsample) < 0)
THROW_TJ("setting TJPARAM_FASTUPSAMPLE");
if (tj3Set(tjInstance, TJPARAM_FASTDCT, fastDCT) < 0)
THROW_TJ("setting TJPARAM_FASTDCT");
if (tj3DecompressHeader(tjInstance, jpegBuf, jpegSize) < 0)
THROW_TJ("reading JPEG header");
width = tj3Get(tjInstance, TJPARAM_JPEGWIDTH);
height = tj3Get(tjInstance, TJPARAM_JPEGHEIGHT);
inSubsamp = tj3Get(tjInstance, TJPARAM_SUBSAMP);
inColorspace = tj3Get(tjInstance, TJPARAM_COLORSPACE);
if (tj3Get(tjInstance, TJPARAM_LOSSLESS))
scalingFactor = TJUNSCALED;
printf("Input Image: %d x %d pixels, %s subsampling, %s colorspace\n",
width, height, subsampName[inSubsamp], colorspaceName[inColorspace]);
if (tj3SetScalingFactor(tjInstance, scalingFactor) < 0)
THROW_TJ("setting scaling factor");
width = TJSCALED(width, scalingFactor);
height = TJSCALED(height, scalingFactor);
if (outSubsamp < 0)
outSubsamp = inSubsamp;
pixelFormat = TJPF_BGRX;
if ((unsigned long long)width * height * tjPixelSize[pixelFormat] >
(unsigned long long)((size_t)-1))
THROW("allocating uncompressed image buffer", "Image is too large");
if ((imgBuf =
(unsigned char*)malloc(sizeof(unsigned char) * width * height *
tjPixelSize[pixelFormat])) == NULL)
THROW_UNIX("allocating uncompressed image buffer");
if (tj3Decompress8(tjInstance, jpegBuf, jpegSize, imgBuf, 0,
pixelFormat) < 0)
THROW_TJ("decompressing JPEG image");
printf("\n");
if (tj3SaveImage8(tjInstance, "decode_rgb_image.bmp", imgBuf, width, 0, height,
pixelFormat) < 0)
THROW_TJ("saving output image");
bailout:
free(imgBuf);
tj3Free(jpegBuf); jpegBuf = NULL;
tj3Destroy(tjInstance);
if (jpegFile) fclose(jpegFile);
return retval;
}