0

I have a problem with this function. The result it's giving doesn't match the original data. I can't find the cause of the problem. Encoding and decoding png works fine, but as i save and load the pixels raw data between encoding, it cannot be read.

#include <stdio.h>
#include <tchar.h>
#include "lodepng.h"
void ProcessImage(const char* scrPath, const char* tmpPath, const char* dstPath)
{
    unsigned error;
    unsigned char* pixelRaw;
    unsigned width, height;

    //load png
    error = lodepng_decode32_file(&pixelRaw, &width, &height, scrPath);
    if(error) 
        printf("error %u: %s\n", error, lodepng_error_text(error));

    //save pixels raw to file
    ofstream* _stream = new ofstream(tmpPath, ios::out|ios::binary);
    _stream->write(reinterpret_cast<const char*>(&pixelRaw), width * height);
    _stream->close();
    delete _stream;

    char* pixelRawTmp;
    unsigned char* pixelRaw2;

    // load pixels raws from file
    ifstream* _stream2 = new ifstream(tmpPath, ios::in|ios::binary);
    _stream2->read(pixelRawTmp,width*height);
    pixelRaw2 = reinterpret_cast<unsigned char*>(pixelRawTmp);
    delete _stream2;

    // saving png
    error = lodepng_encode32_file(dstPath, pixelRaw2, width, height);
    if(error) 
        printf("error %u: %s\n", error, lodepng_error_text(error));

    free(pixelRaw);
    free(pixelRawTmp);
    free(pixelRaw2);
}
  • 1
    Why are you allocating `ofstream`/`ifstream` with `new`? You don't do that in in c++ for short lived objects. This kind of objects can be allocated on the stack; it is Java, C# and other languages that force you allocate objects with `new`. In c++, you should just do `ifstream stream2(tmpPath, ios::in|ios::binary);` This is not related to your problem, but is definitely something you should change. – glampert Sep 06 '14 at 02:23
  • Thanks for advices. You guess good, i programm mainly on C#. I will change that – Wilony Fox Sep 06 '14 at 02:26
  • From [this example](http://lodev.org/lodepng/example_decode.c), I would expect the size of the data read to be `width` times `height` _times the size of a RGBA pixel_ (presumably 32-bits from the name of the function). – SleuthEye Sep 06 '14 at 02:27
  • 2
    You are also `read()`ing into `pixelRawTmp` without allocating any memory for it. – T.C. Sep 06 '14 at 02:42
  • I suspect you need to use `_stream->write(pixelRaw, width * height);` instead of `_stream->write(reinterpret_cast(&pixelRaw), width * height);` – R Sahu Sep 06 '14 at 03:04
  • I cannot give an unsigned char* on the _stream->write(). VS raise an error – Wilony Fox Sep 06 '14 at 21:44

0 Answers0