Jimp: how to center the text and undo text after writing it

Created on 24 Dec 2016  路  2Comments  路  Source: oliver-moran/jimp

First of all, thank you for the FANTASTIC library, you literally saved from me from committing suicide 馃槃
I saw @Ratismal open a PR for aligning text but I think you havent incorporated the PR yet, i want the text to be centered horizontally and vertically regardless of image size. how do I go about it. Thanks for your answers in advance. How do I find the width in pixels occupied by my text

EDIT 1
I figured out how to center the text, I am using your measureText function

SECOND PART

After writing some text,i would like to get its base 64 url and then undo the changes, or remove the text, how do I do that

UPDATE 1

I did it

Most helpful comment

jimp.text = function (image, text) {
    return new Promise((resolve, reject) => {
        Jimp.loadFont(Jimp.FONT_SANS_128_WHITE).then(function (font) {
            let totalWidth = measureText(font, text)
            image.print(font, Math.floor(width / 2 - totalWidth / 2), Math.floor(height / 2 - 64), text);
            resolve(image)
        });
    })

}

function measureText(font, text) {
    var x = 0;
    for (var i = 0; i < text.length; i++) {
        if (font.chars[text[i]]) {
            x += font.chars[text[i]].xoffset
                + (font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0)
                + (font.chars[text[i]].xadvance || 0);
        }
    }
    return x;
};

how do i get the height instead of hard coding 64

All 2 comments

Hi @slidenerd can you please explain how you centered the text? Thank you

jimp.text = function (image, text) {
    return new Promise((resolve, reject) => {
        Jimp.loadFont(Jimp.FONT_SANS_128_WHITE).then(function (font) {
            let totalWidth = measureText(font, text)
            image.print(font, Math.floor(width / 2 - totalWidth / 2), Math.floor(height / 2 - 64), text);
            resolve(image)
        });
    })

}

function measureText(font, text) {
    var x = 0;
    for (var i = 0; i < text.length; i++) {
        if (font.chars[text[i]]) {
            x += font.chars[text[i]].xoffset
                + (font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0)
                + (font.chars[text[i]].xadvance || 0);
        }
    }
    return x;
};

how do i get the height instead of hard coding 64

Was this page helpful?
0 / 5 - 0 ratings

Related issues

laino picture laino  路  5Comments

dtrofimov picture dtrofimov  路  5Comments

PainKKKiller picture PainKKKiller  路  5Comments

maqboolkhan picture maqboolkhan  路  5Comments

haydenbleasel picture haydenbleasel  路  6Comments