Home > Software design >  How to replace text in Gimp image programatically
How to replace text in Gimp image programatically

Time:09-17

As in the title - imagine there is some Gimp .xcf file containing many layers. Part of these layers contain text. Is there any format I can export .xcf file to, that it somehow preserve 'human readable' text ?

The final goal is to process that text and put it again into the file, I am aware that this sounds unusual but maybe some of you have an idea how to achieve scenario like that.

I did some research and I saw I can export image to .psd format and then using NPM package process that image and extract text. This is just partially solves the problem, because I will not know how to put the processed text back into this .psd file (unless I decompile this NPM package and try to write some implementation myself...)

Any solutions and alternatives higly appreciated

CodePudding user response:

You can script Gimp (using Scheme or Python). Technically you cannot change the text in a layer (there is no API for that), but you can recover the characteristics of a text layer (original text, font type, font size...) and recreate a new layer with a new text. Here is some Python code to recover the text information:

def text_info(img,layer):
    parasites=None
    try:
        parasites=layer.parasite_list()
    except Exception as e:
        pass;
    if parasites and 'gimp-text-layer' in parasites:
        data=layer.parasite_find('gimp-text-layer').data
        pdb.gimp_message('Text layer "%s": %s' % (layer.name,data))
    else:
        pdb.gimp_message('No text information found for layer "%s"' % layer.name)

(this information is only present of the file has been saved, it is not available on a newly created layer, but this shouldn't bea problem in your case)

Of course if the text is in a plain bitmap layer of its own this cannot be done, you have to guess the font type & size (but sometimes the code above can still recover the text information)

But if your XCF has a simple structure, it can be a lot simpler to decompose it into individual images, and build a new image with ImageMagick, using some of these layers plus new text images (or directly rendered text).

  • Related