Change/Overlay color on single-colored PNG image with transparent background?

Question:

What I would like to be able to do is dynamically change a solid single-colored png to another color simply by inputting the desired color code without losing the transparent background. The implementations I’ve seen tend to be a bit sloppy, so I was wondering if anyone can give me advice on how they would implement it.

I’d be most comfortable with a PHP solution but Python works too, hell I’ll even take a good canvas solution. Any advice/examples regarding this would be very much appreciated, thanks guys.

Asked By: Ian

||

Answers:

Here’s a simple canvas implementation:

colorize = function(image, r, g, b) {

    var newImg = $('<canvas>')[0];
    newImg.width = image.width;
    newImg.height = image.height;
    var newCtx = newImg.getContext('2d');
    newCtx.drawImage(image, 0, 0);

    var imageData = newCtx.getImageData(0, 0, image.width, image.height);
    data = imageData.data;
    for (var i = 0; i < data.length; i += 4) {
        data[i+0] = r;
        data[i+1] = g;
        data[i+2] = b;
    }
    newCtx.putImageData(imageData, 0, 0);

    return newImg;
};

JSFiddle: http://jsfiddle.net/bK7P9/6/

Answered By: LukeGT

You can do this using PIL and numpy in Python. Assuming we have a method NewSolidImage (which we’ll define below), we can turn an image into an array of pixels, use the method to convert the pixels and then save to a new file:

import numpy
from PIL import Image

def CreateNewImage(current_filename, new_filename, new_color):
  image = Image.open(current_filename)
  image_values = numpy.array(image)

  new_image_values = NewSolidImage(image_values, new_color)
  new_image = Image.fromarray(new_image_values)

  new_image.save(new_filename)

Now to define this method. We simply take an array, make sure it is the shape that we expect and then on pixels that aren’t 100% transparent, we set the red, green, blue values to those of the solid passed in.

def NewSolidImage(rgba_array, new_color):
  new_r, new_g, new_b = new_color

  rows, cols, rgba_size = rgba_array.shape
  if rgba_size != 4:
    raise ValueError('Bad size')

  for row in range(rows):
    for col in range(cols):
      pixel = rgba_array[row][col]
      transparency = pixel[3]
      if transparency != 0:
        new_pixel = pixel.copy()
        new_pixel[0] = new_r
        new_pixel[1] = new_g
        new_pixel[2] = new_b

        rgba_array[row][col] = new_pixel

  return rgba_array
Answered By: bossylobster

Ordinarily I like to work in the RGB color space, but this is a case where HLS works very well. The conversion in Python is simple, by replacing the H and S and leaving L the same.

import colorsys
from PIL import Image

def recolor(im, r, g, b):
    h, l, s = colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
    result = im.copy()
    pix = result.load()
    for y in range(result.size[1]):
        for x in range(result.size[0]):
            r2, g2, b2, a = pix[x, y]
            h2, l2, s2 = colorsys.rgb_to_hls(r2/255.0, g2/255.0, b2/255.0)
            r3, g3, b3 = colorsys.hls_to_rgb(h, l2, s)
            pix[x, y] = (int(r3*255.99), int(g3*255.99), int(b3*255.99), a)
    return result

recolor(im_flag, 255, 0, 0).save(r'c:tempred_flag.png')

original result with (255,0,0)

Answered By: Mark Ransom