2

I'm trying to convert an array of integers to a PNG-file.

function saveImg(data, dir, name, waveBand) {
    if (!fs.existsSync(dir)){
        logger.info(dir + ' does not exist... creating!');
        fs.mkdirSync(dir);
    }

    logger.info('received data with length ' + data.length);
    try {
        const encoder = new util.TextDecoder("utf-8");
        const decodedData = encoder.decode(new Uint8Array(data));
        logger.info('decoded string: ' + decodedData);
        const imgLocation = path.join(getStoragePublicFolder(), dir, name + '.png');
        logger.info('Writing image to location: ' + imgLocation);

        fs.writeFile(path.resolve(imgLocation), decodedData,
            function(err) {
                if(err) 
                    logger.info(err);
            }
        );

        logger.info('Success! Image saved to ' + imgLocation);
        return imgLocation;
    } 
    catch (err)
    { 
        logger.error('Failed to save image - ' + err); 
    }
    return defaultPath(waveBand);
}

My data looks like this: https://jsfiddle.net/ebaxg3q4/

Unfortunately there is something wrong with the decoding of the data therefore the image is corrupted.

Which kind of encoding is this? What is the error I made?

Thank you in advance!

1
  • 2
    You're trying to decode the data as UTF-8 text. It's not text but the actual bytes that should be saved to the file. Commented Nov 6, 2019 at 10:42

1 Answer 1

4

You can create a buffer from your station bitmap data using Buffer.from(Array).

We can then use fs.writeFile to write the buffer to the .png file.

This code works for me (using your sample data):

function saveImg(data, dir, name, waveBand) {
    if (!fs.existsSync(dir)){
        logger.info(dir + ' does not exist... creating!');
        fs.mkdirSync(dir);
    }

    logger.info('received data with length ' + data.length);
    try {
        const decodedData = Buffer.from(data);
        const imgLocation = path.join(getStoragePublicFolder(), dir, name + '.png');
        logger.info('Writing image to location: ' + imgLocation);
        fs.writeFile(path.resolve(imgLocation), decodedData,
            function(err) {if(err) logger.info(err);});
        logger.info('Success! Image saved to ' + imgLocation);
        return imgLocation;
    } catch (err){ logger.error('Failed to save image - ' + err); }
    return defaultPath(waveBand);
}

// Use the first station in the station list.
saveImg(dummyStation.stationList[0].stationIconPicture.data.data, "./test", "station");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.