View Single Post
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 869
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Overlaying graphics in Python?

 
0
  #2
Jun 7th, 2008
Here is an example using PIL ...
  1. # generate a true opaque watermark with the Python Image Library (PIL)
  2. # free download from: http://www.pythonware.com/products/pil/
  3.  
  4. from PIL import Image, ImageEnhance
  5.  
  6. def reduce_opacity(im, opacity):
  7. """returns an image with reduced opacity"""
  8. assert opacity >= 0 and opacity <= 1
  9. if im.mode != 'RGBA':
  10. im = im.convert('RGBA')
  11. else:
  12. im = im.copy()
  13. alpha = im.split()[3]
  14. alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
  15. im.putalpha(alpha)
  16. return im
  17.  
  18. def watermark(im, mark, position, opacity=1):
  19. """adds a watermark to an image"""
  20. if opacity < 1:
  21. mark = reduce_opacity(mark, opacity)
  22. if im.mode != 'RGBA':
  23. im = im.convert('RGBA')
  24. # create a transparent layer the size of the image and draw the
  25. # watermark in that layer.
  26. layer = Image.new('RGBA', im.size, (0,0,0,0))
  27. if position == 'tile':
  28. for y in range(0, im.size[1], mark.size[1]):
  29. for x in range(0, im.size[0], mark.size[0]):
  30. layer.paste(mark, (x, y))
  31. elif position == 'scale':
  32. # scale, but preserve the aspect ratio
  33. ratio = min(
  34. float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
  35. w = int(mark.size[0] * ratio)
  36. h = int(mark.size[1] * ratio)
  37. mark = mark.resize((w, h))
  38. layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
  39. else:
  40. layer.paste(mark, position)
  41. # composite the watermark with the layer
  42. return Image.composite(layer, im, layer)
  43.  
  44. def test():
  45. # pick images you have ...
  46. im = Image.open('Audi.jpg')
  47. mark = Image.open('Audi2.jpg')
  48. watermark(im, mark, 'tile', 0.3).show()
  49. # also try these ...
  50. #watermark(im, mark, 'scale', 0.3).show()
  51. #watermark(im, mark, (10, 10), 0.5).show()
  52.  
  53. if __name__ == '__main__':
  54. test()
I hope that is the sort of thing you meant.
May 'the Google' be with you!
Reply With Quote