thomaskekeisen.de

From the life of a screen worker

Initial situation

For our game KärcheRPG we developed at the Hackathon Stuttgart 2016, we used graphics from kenny.nl. This images are called "tilemaps", graphics, that contain many small graphics in a certain size. This format is basically used for the development of a map in a 2D game. The javascript game engine phaser.js we used already supports tilemaps by default. Our map is created with the program Tiled.

The problem: In the free graphics provided by kenny.nl is always a gap with a width of one pixel between each "asset". Because we did not manage it to set up our game configuration in a way that ignores that space, we simply wanted to remove it from the graphic at all. Since I was too lazy to remove all the gaps manually and I realized that I had written a script that will do this work for me in a fraction of that time I needed, I actually wrote this script.

A quicky with Jimp

Because our server was based anyway on node.js, I had searched directly for a corresponding library in javascript. The first hit was Jimp ("JavaScript Image Manipulation Program"), which finally was the best choice to fix my problem.

        
            var Jimp = require('jimp');

            Jimp.read('input.png', function (err, sourceMap) {
                var tileSize  = 16;
                var spaceSize = 1;
                var tilesX    = (sourceMap.bitmap.width  + 1) / (tileSize + spaceSize);
                var tilesY    = (sourceMap.bitmap.height + 1) / (tileSize + spaceSize);

                var newSize = {
                    height: tileSize * tilesY,
                    width:  tileSize * tilesX
                };

                var targetImage = new Jimp(newSize.width, newSize.height, function (error, newImage) {
                    for (var x = 0; x < tilesX; ++x {
                        for (var y = 0; y < tilesY; ++y) {
                            newImage.blit(
                                sourceMap,
                                x  * tileSize,
                                y  * tileSize,
                                (x * (tileSize + spaceSize)),
                                (y * (tileSize + spaceSize)),
                                tileSize,
                                tileSize
                            );
                        }
                    }

                    newImage.write('output.png');
                });
            });
        
    

The script above opens an image from the path input.png and removes one pixel every 16 pixels. If these values has to be adjusted, only the variables tileSize and spaceSize have to be changed. The new tilemap is saved under the path output.png . Jimp itself is installed with a simple npm install --save jimp .

Share

Comments