使用libjpeg-turbo进行无损读/写

时间:2018-11-17 16:08:52

标签: c++ image libjpeg-turbo

我正在尝试使用libjpeg-turbo存储和检索图像,我尝试了以下代码,但与原始图像进行比较时会导致丢失。

CompressSave()使用cv :: Mat,其中包含需要另存为jpg文件的图像数据。

我将需要存储的图像数据传递到CompressSave(),它将压缩数据并将其存储为JPG。 DeCompressRead()用于读取数据并从存储的图像中解压缩。

我错过了任何参数吗?

自从保存tjSave导致崩溃后,我就使用了文件处理功能。

void CompressSave(cv::Mat img, std::string filename)
{
    const int JPEG_QUALITY = 100;
    const int COLOR_COMPONENTS = 3;
    int _width = img.rows;
    int _height = img.cols;
    long unsigned int _jpegSize = 0;
    unsigned char* _compressedImage = NULL; //!< Memory is allocated by tjCompress2 if _jpegSize == 0
    unsigned char* buffer = img.data;

    tjhandle _jpegCompressor = tjInitCompress();

    tjCompress2(_jpegCompressor, buffer, _width, 0, _height, TJPF_RGB,
        &_compressedImage, &_jpegSize, TJSAMP_444, JPEG_QUALITY,
        TJFLAG_ACCURATEDCT);

    tjDestroy(_jpegCompressor);

    FILE *file = fopen(filename.c_str(), "wb");
    if (!file) {
        std::cout << "Could not open JPEG file: " << strerror(errno);
        return;
    }
    if (fwrite(_compressedImage, _jpegSize, 1, file) < 1) {
        cerr << "Could not write JPEG file: " << strerror(errno);
        return;
    }
    fclose(file);

    //to free the memory allocated by TurboJPEG (either by tjAlloc(), 
    //or by the Compress/Decompress) after you are done working on it:
    tjFree(_compressedImage);
}

unsigned char* DeCompressRead(std::string fileName)
{
    const int JPEG_QUALITY = 100;
    const int COLOR_COMPONENTS = 3;
    int _width;
    int _height;
    long unsigned int _jpegSize = 0;
    unsigned char* _compressedImage; //!< Memory is allocated by tjCompress2 if _jpegSize == 0

    long size;
    int inSubsamp, inColorspace;
    unsigned long jpegSize;
    unsigned char* jpegBuf = nullptr;

    unsigned char *imgBuf = nullptr;
    int align(0);
    //int pixelFormat;
    int flags(0);

    FILE *jpegFile = nullptr;
    jpegFile = fopen(fileName.c_str(), "rb");

    fseek(jpegFile, 0, SEEK_END);
    size = ftell(jpegFile);
    fseek(jpegFile, 0, SEEK_SET);

    jpegSize = (unsigned long)size;
    jpegBuf = (unsigned char *)tjAlloc(jpegSize);

    fread(jpegBuf, jpegSize, 1, jpegFile);
    fclose(jpegFile);  jpegFile = NULL;


    tjhandle _jpegDecompressor = tjInitDecompress();
    int jpegSubsamp;
    tjDecompressHeader2(_jpegDecompressor, jpegBuf, jpegSize, &_width, &_height, &jpegSubsamp);

    int pixelFormat = TJPF_RGB;
    imgBuf = (unsigned char *)tjAlloc(_width * _height * tjPixelSize[pixelFormat]);
    tjDecompress2(_jpegDecompressor, jpegBuf, jpegSize, imgBuf, _width, 0/*pitch*/, _height, TJPF_RGB, TJFLAG_ACCURATEDCT);

    tjDestroy(_jpegDecompressor);

    return imgBuf;
}

0 个答案:

没有答案