jpg_loader: introduced jpg decode using libjpeg-turbo fix #1

Added bool open(const char* data, uint32_t size, bool copy);
This commit is contained in:
Michal Maciola 2021-07-02 10:23:13 +02:00 committed by Hermet Park
parent 0435f29f11
commit eddbb4d71d
2 changed files with 44 additions and 6 deletions

View file

@ -20,9 +20,26 @@
* SOFTWARE.
*/
#include <memory.h>
#include "tvgLoaderMgr.h"
#include "tvgJpgLoader.h"
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
void JpgLoader::clear()
{
tjFree(data);
data = NULL;
pointer = NULL;
size = 0;
}
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
JpgLoader::JpgLoader()
{
jpegDecompressor = tjInitDecompress();
@ -37,6 +54,8 @@ JpgLoader::~JpgLoader()
bool JpgLoader::open(const string& path)
{
clear();
bool success = false;
FILE *jpegFile = NULL;
if ((jpegFile = fopen(path.c_str(), "rb")) == NULL) return false;
@ -46,24 +65,40 @@ bool JpgLoader::open(const string& path)
if (((size = ftell(jpegFile)) < 1)) goto finalize;
if (fseek(jpegFile, 0, SEEK_SET)) goto finalize;
if (data) tjFree(data);
data = (unsigned char *) tjAlloc(size);
if (!data) goto finalize;
if (fread(data, size, 1, jpegFile) < 1) goto failure;
pointer = data;
success = true;
goto finalize;
failure:
tjFree(data);
data = NULL;
clear();
finalize:
fclose(jpegFile);
return success;
}
bool JpgLoader::open(const char* data, uint32_t size, bool copy)
{
clear();
if (copy) {
this->data = (unsigned char *) malloc(size);
if (!this->data) return false;
memcpy((unsigned char *)this->data, data, size);
this->pointer = this->data;
} else {
this->pointer = (unsigned char *)data;
}
this->size = size;
return true;
}
bool JpgLoader::read()
{
int width, height;
@ -80,7 +115,7 @@ bool JpgLoader::read()
//decompress jpg image
if (tjDecompress2(jpegDecompressor, data, size, image, width, 0, height, TJPF_BGRX, 0) < 0) {
tjFree(image);
data = NULL;
image = NULL;
return false;
}
@ -91,8 +126,7 @@ bool JpgLoader::read()
bool JpgLoader::close()
{
tjFree(data);
data = NULL;
clear();
return true;
}

View file

@ -32,14 +32,18 @@ public:
using Loader::open;
bool open(const string& path) override;
bool open(const char* data, uint32_t size, bool copy) override;
bool read() override;
bool close() override;
const uint32_t* pixels() override;
private:
void clear();
tjhandle jpegDecompressor;
unsigned char* data = nullptr;
const unsigned char* pointer = nullptr;
unsigned long size = 0;
unsigned char *image = nullptr;
};