Walter Moore
Walter Moore

Reputation: 77

Gimp python-fu script to select everything with a given color and change it to a different color

I am writing a plugin script that will open a file, select by color, change the selection to a new color, save image as a new file.

I don't know how to change the color to a new color. Can someone provide guidance?

This is what I have so far:

  # open input file
  theImage = pdb.gimp_file_load(in_filename, in_filename)

  # get the active layer
  drawable = pdb.gimp_image_active_drawable(theImage)

  # select everything in the image with the color that is to be replaced
  pdb.gimp_image_select_color(theImage, CHANNEL_OP_REPLACE, drawable, colorToReplace)

  # need to do something to change the color from colorToReplace to the newColor
  # but I have no idea how to change the color.

  # merge the layers to maintain transparency
  layer = pdb.gimp_image_merge_visible_layers(theImage, CLIP_TO_IMAGE)

  # save the file to a new filename
  pdb.gimp_file_save(theImage, layer, out_filename, out_filename)

Upvotes: 3

Views: 3647

Answers (1)

xenoid
xenoid

Reputation: 8904

You just need to bucket-fill the selection:

pdb.gimp_drawable_edit_fill(drawable, fill_type)

This fills the selection with the current foreground/background color (depending on fill_type). If you need to set this color in your plugin:

import gimpcolor

color=gimpcolor.RGB(0,255,0)  # integers in 0->255 range)
color=gimpcolor.RGB(0.,1.,0.) # Floats in 0.->1. range)

pdb.gimp_context_set_foreground(color)

Note that this answer your technical question, but it is likely that this is not what you want to do (pixelated edges, remaining halos, etc...). The good technique is normally to replace the initial color with transparency (paint in Color Erase mode) and then fill the holes with the new color in Behind mode. For instance, to replace the FG color by the BG one:

pdb.gimp_edit_bucket_fill(layer,FG_BUCKET_FILL,COLOR_ERASE_MODE,100.,0.,0,0.,0.)
pdb.gimp_edit_bucket_fill(layer,BG_BUCKET_FILL,BEHIND_MODE, 100.,0.,0,0.,0.)

If you don't want to change other mixed colors in your image, keep you color selection, grow it by one pixel before applying the two paint operations. Growing the selection makes the operations above apply to the pixels on the edges, which is where this is really important.

Upvotes: 1

Related Questions