Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

applying image decoration (border) in Python (programmatically)

I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border.

Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) .

Here is what I am looking for:

import fooImageBorders 
import Image 

foo = Image.open("someImage.jpg")
foo2 = fooImageBorders.bevel(foo, color = black)

...I can write my own methods to add borders .. but if there is already something like this out there with a comprehensive set of border options, I would like to make use of it.

I looked at PIL documentation and couldn't find a way to do this. I have windows xp and there doesn't seem to be a way to install PythonMagick either for Python 2.6 if you don't have cygwin.

like image 505
apt Avatar asked Jan 03 '10 18:01

apt


People also ask

How do you add a border in Python?

Create a frame with Frame() method. Highlight the border of the frame with a color, highlightbackground="blue". Then, set the thickness of the border, highlightthickness=2. Next, create some widgets inside the frame.


3 Answers

Look at the ImageOps module within the PIL.

import Image
import ImageOps

x = Image.open('test.png')
y = ImageOps.expand(x,border=5,fill='red')
y.save('test2.png')
like image 97
Mark Avatar answered Oct 04 '22 08:10

Mark


You can use the PythonMagick module. the documentation for this module is here (Magic ++ documentation)

Example: To add a red 2 pixel border to an image, you need following code.

from PythonMagick import Image
i = Image('example.jpg') # reades image and creates an image instance
i.borderColor("#ff0000") # sets border paint color to red
i.border("2x2") # paints a 2 pixel border
i.write("out.jpg")
# writes the image to a file 
like image 29
Phong Avatar answered Oct 03 '22 08:10

Phong


foo2 = foo.copy()
draw = ImageDraw.Draw(foo2)
for i in range(width):
    draw.rectangle([i, i, foo2.size[0]-i-1, foo2.size[1]-i-1], outline = color)

foo2 will have a width-pixel border of color.

If you want different colored borders on each side, you can replace .rectangle with repeated .line calls.

If you want the border not to cover any part of the existing image, use this instead of foo.copy().

foo2 = Image.new(foo.mode, (foo.size[0] + 2*width, foo.size[1] + 2*width))
foo2.paste(foo, (width, width))
like image 24
ephemient Avatar answered Oct 02 '22 08:10

ephemient