Rectangle 27 1

import StringIO, base64, logging, operator

import dxfgrabber
import Image, ImageDraw, ImageFont #PIL

from homcoord import *

def rint(x):return int(round(x))

class BBox:
    """bounding box"""
    def __init__(self,pt1=None,pt2=None):
        self._corner1=None
        self._corner2=None
        if pt1: self+=pt1
        if pt2: self+=pt2

    def __iadd__(self,pt):
        if isinstance(pt,BBox):
            self+=pt._corner1
            self+=pt._corner2
        else:
            if not self._corner1:
                self._corner1=pt
            else:
                self._corner1=Pt(map(min,zip(self._corner1.xy,pt.xy)))
            if not self._corner2:
                self._corner2=pt
            else:
                self._corner2=Pt(map(max,zip(self._corner2.xy,pt.xy)))
        return self

    def __repr__(self):
        return "BBox(%s,%s)"%(self._corner1,self._corner2)

    def __call__(self):
        """:return: list of flatten corners"""
        l=list(self._corner1.xy)
        l.extend(list(self._corner2.xy))
        return l

    def size(self):
        """:return: Pt with xy sizes"""
        return self._corner2-self._corner1

    def center(self):
        """:return: Pt center"""
        res=self._corner2+self._corner1
        return res/2

    def trans(self,trans):
        """
        :param trans: Xform
        :return: BBox = self transformed by trans
        """
        return BBox(trans(self._corner1),trans(self._corner2))

def cbox(c,r):
    """ bounding box of a circle
    :param c: Pt center
    :param r: float radius
    :return: BBox
    """
    rr=Pt(r,r)
    return BBox(c+rr,c-rr)

def Trans(scale=1, offset=[0,0], rotation=0):
    res=Xform([[scale,0,offset[0]],[0,scale,offset[1]],[0,0,1]])
    if rotation:
        res=Xrotate(rotation*pi/180.)*res
    return res

class DXF:
    def __init__(self, file, layers=None, ignore=[]):
        """reads a .dxf file
        :param file: string path to .dxf file to read
        :param layers: list or dictionary of layers to handle. Empty = all layers
        :param ignore: list of strings of entity types to ignore
        """
        self.dxf=dxfgrabber.readfile(file)
        self.layers=layers
        self.ignore=ignore

    def entities(self,ent=None):
        """iterator over dxf or block entities"""
        if not ent:
            ent=self.dxf.entities
        for e in ent:
            if self.layers and e.layer not in self.layers:
                continue
            elif e.dxftype in self.ignore:
                continue
            else: 
                yield e

    def bbox(self):
        """:return: :class:BBox dwg enclosing bounding box"""
        box=BBox()
        for e in self.entities():
            if e.dxftype=='LINE':
                box+=Pt(e.start[:2])
                box+=Pt(e.end[:2])
            elif e.dxftype == 'CIRCLE':
                box+=cbox(Pt(e.center[:2]),e.radius)
            elif e.dxftype == 'ARC':
                c=Pt(e.center[:2])
                a=e.endangle-e.startangle
                if a>0:
                    start=e.startangle
                else: #arc goes clockwise (step will be negative)
                    start=e.endangle
                n=rint(abs(a)/10.) # number of points each 10 approximately
                n=max(n,1)
                step=a/n #angle between 2 points, might be negative
                for i in range(n+1):
                    box+=c.radial(e.radius,radians(start+i*step))
            elif e.dxftype=='POLYLINE':
                for v in e.vertices:
                    box+=Pt(v.location[:2])
            elif e.dxftype=='BLOCK': 
                pass #TODO ...
            elif e.dxftype in ['TEXT','INSERT']:
                box+=Pt(e.insert[:2])
            else:
                logging.warning('Unknown entity %s'%e)
        return box

    def _draw(self,draw,entities,trans,pen="black"):
        for e in entities:
            if e.dxftype=='LINE':
                b=list(trans(Pt(e.start[:2])).xy)
                b.extend(list(trans(Pt(e.end[:2])).xy))
                draw.line(b,fill=pen)
            elif e.dxftype=='CIRCLE':
                b=cbox(Pt(e.center[:2]),e.radius)
                b=b.trans(trans)
                draw.ellipse(b(),outline=pen)
            elif e.dxftype=='ARC':
                c=Pt(e.center[:2])
                b=cbox(c,e.radius)
                b=b.trans(trans)
                b=map(rint,b())
                startangle=degrees(trans.angle(radians(e.startangle)))
                endangle=degrees(trans.angle(radians(e.endangle)))
                startangle,endangle=endangle,startangle #swap start/end because of Y symmetry
                draw.arc(b,int(startangle),int(endangle),fill=pen)
            elif e.dxftype=='POLYLINE':
                b=[]
                for v in e.vertices:
                    b.extend(list(trans(Pt(v.location[:2])).xy))
                draw.line(b,fill=pen)
            elif e.dxftype=='TEXT':
                h=e.height*trans.mag()
                pt=Pt(e.insert[:2])+Pt(0,e.height) #ACAD places texts by top left point...
                font=None
                try:
                    font = ImageFont.truetype("c:/windows/fonts/Courier New.ttf", rint(h))
                except:
                    pass
                if not font:
                    h=h*1.4 #magic factor ...
                    fh=[8,10,12,14,16,18,20,22,24,26,28,30,36,40,48,60]
                    i,h=min(enumerate(fh), key=lambda x: abs(x[1]-h)) #http://stackoverflow.com/questions/9706041/finding-index-of-an-item-closest-to-the-value-in-a-list-thats-not-entirely-sort
                    import os
                    path=os.path.realpath(__file__)
                    path=os.path.dirname(path)
                    font = ImageFont.load(path+'\\base_pil\\72\\Courier New_%s_72.pil'%h)
                draw.text(trans(pt).xy,e.text,font=font,fill=pen) 
            elif e.dxftype=='INSERT': 
                t2=Trans(1,e.insert,e.rotation).compose(trans)

                self._draw(draw,self.entities(self.dxf.blocks[e.name]._entities),t2,pen)
            elif e.dxftype=='BLOCK': 
                pass # block definition is automatically stored in dxf.blocks dictionary
            else:
                logging.warning('Unknown entity %s'%e)

    def img(self,size=[256,256],back="white",pen="black",border=5,antialias=1):
        """:result: :class:`PIL:Image` rasterized image"""
        box=self.bbox()
        from Goulib.math2 import product
        if not product(box.size().xy): # either x or y ==0
            return None

        s=map(operator.div,[float(x-border)*antialias if x else 1E9 for x in size ],box.size().xy)
        trans=Trans(scale=min(s))
        size=trans(box.size())+Pt(2*antialias*border,2*antialias*border) #add borders as an offset
        offset=size/2-trans(box.center()) #offset in pixel coordinates
        trans=trans*Trans(offset=offset.xy)
        trans=trans*Xscale(1,-1) #invert y axis
        trans=trans*Xlate(0,size.y) #origin is lower left corner

        img = Image.new("RGB", map(rint,size.xy), back)
        self._draw(ImageDraw.Draw(img), self.entities(), trans, pen)
        if antialias>1:
            size=size/antialias
            img=img.resize(map(rint,size.xy), Image.ANTIALIAS)
        return img

def img2base64(img,fmt='PNG'):
    """
    :param img: :class:`PIL:Image`
    :result: string base64 encoded image content in specified format
    :see: http://stackoverflow.com/questions/14348442/django-how-do-i-display-a-pil-image-object-in-a-template
    """
    output = StringIO.StringIO()
    img.save(output, fmt)
    output.seek(0)
    output_s = output.read()
    return base64.b64encode(output_s)

if __name__ == '__main__':
    dxf=DXF("..\\tests\\FERRO_01.DXF")
    img=dxf.img(size=[1280,None],border=50)
    print img2base64(img)
    img.save('..\\tests\\out.png')

I tried that but I had troubles with this library "homcoord". I use Mac OSX Yosemite. Actually this is good suggestion. Maybe I have to read more carefully about this library.

Convert dxf to bmp write on python - Stack Overflow

python
Rectangle 27 0

I figured it out ! In case anyone is wondering, I added :

point = ( int(header.width * 0.5), int(header.height * 0.5))
header1.paste( foreground, point )

Python - Draw text or image on top of background image with relative p...

python pillow
Rectangle 27 0

PIL doesn't support this but you can fake it: Render the text four or eight times with the outline color using one pixel offsets:

x+1,y
x-1,y
x  ,y+1
x  ,y-1
x+1,y+1
x  ,y+1
x-1,y+1

x+1,y
x-1,y

x+1,y-1
x  ,y-1 
x-1,y-1

and then once at x,y with the fill color.

How can I draw text with different stroke and fill colors on images wi...

python image python-imaging-library
Rectangle 27 0

You could use that page for creating the image right there instead of implementing the routine yourself but the code is included on the page too.

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import StringIO

filter_dict = {
    'BLUR' : ImageFilter.BLUR,
    'CONTOUR' : ImageFilter.CONTOUR,
    'DETAIL' : ImageFilter.DETAIL,
    'EDGE_ENHANCE' : ImageFilter.EDGE_ENHANCE,
    'EDGE_ENHANCE_MORE' : ImageFilter.EDGE_ENHANCE_MORE,
    'EMBOSS' : ImageFilter.EMBOSS,
    'FIND_EDGES' : ImageFilter.FIND_EDGES,
    'SMOOTH' : ImageFilter.SMOOTH,
    'SMOOTH_MORE' : ImageFilter.SMOOTH_MORE,
    'SHARPEN' : ImageFilter.SHARPEN
}

def get_font_full_path(font_path,font_name):
    ext = '.TTF' if font_name.upper() == font_name else ".ttf"
    return font_path + font_name + ext

def create_image(font_name, font_size, font_color, width, height, back_ground_color, text, img_type="JPEG", image_filter=None):
    font_full_path = get_font_full_path(font_path,font_name)
    font  =  ImageFont.truetype ( font_full_path, font_size )

    im  =  Image.new ( "RGB", (width,height), back_ground_color )
    draw  =  ImageDraw.Draw ( im )
    text_x, text_y = font.getsize(text)
    x = (width - text_x)/2
    y = (height - text_y)/2
    draw.text ( (x,y), text, font=font, fill=font_color )

    if image_filter:
        real_filter = filter_dict[image_filter]
        im = im.filter(real_filter)
    im.save ( "sample.jpg", format=img_type )

It's helpful to also summarize the implementation in case the website you have linked to goes down.

python - draw text to center of the image using PIL - Stack Overflow

python text python-imaging-library
Rectangle 27 0

the problem was the PIL 1.1.7 doesn't work well with windows XP. the same code runs well under linux or with XP but with PIL 1.1.6 mystory is solved

Drawing Hebrew text to and image using Image module (python) - Stack O...

python image hebrew bidirectional
Rectangle 27 0

Looks like there is no standard way of doing this, but you always can implement it.

import Image
import ImageDraw
import ImageFont

def draw_underlined_text(draw, pos, text, font, **options):    
    twidth, theight = draw.textsize(text, font=font)
    lx, ly = pos[0], pos[1] + theight
    draw.text(pos, text, font=font, **options)
    draw.line((lx, ly, lx + twidth, ly), **options)

im = Image.new('RGB', (400, 400), (255,)*3)
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("arial.ttf", 50)

draw_underlined_text(draw, (50, 150), 'Hello PIL!', font, fill=0)
draw_underlined_text(draw, (50, 300), 'Test', font, fill=128)

im.show()

python - Draw underline text with PIL - Stack Overflow

python python-imaging-library underline
Rectangle 27 0

At the bottom is the python version of this lesson which shows you how to load freetype fonts with the Python Image Library (PIL) http://www.pythonware.com/products/pil/

draw text with GLUT / OpenGL in Python - Stack Overflow

python opengl text draw
Rectangle 27 0

It is a syntax error. Adding more parenthesis just makes a new datastructure. Try:

text = Z + " " + title
draw.text ( (20,20), text, font=arial16, fill="white")

and for your save command:

im.save(S)
im.show(S)

Is it possible to use variables in PIL (python)? - Stack Overflow

python variables text python-imaging-library draw
Rectangle 27 0

Just to clarify: each version of the typeface comes in a separate file, eg: Arial.ttf, ArialBold.ttf, etc..

python - Draw bold/italic text with PIL? - Stack Overflow

python text fonts python-imaging-library draw
Rectangle 27 0

PIL won't automatically do this, but you could easily do it yourself using the getsize method in the ImageFont module. That is, if the text is too big, just split it so that it's not, and put the rest on the next line. (You may want to do this recursively in case the text spans multiple lines.)

python imaging library draw text new line how to? - Stack Overflow

python-imaging-library
Rectangle 27 0

Using cairo (with much code taken from here):

import cairo

def text_extent(font, font_size, text, *args, **kwargs):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
    ctx = cairo.Context(surface)
    ctx.select_font_face(font, *args, **kwargs)
    ctx.set_font_size(font_size)
    return ctx.text_extents(text)

text='Example'
font="Sans"
font_size=55.0
font_args=[cairo.FONT_SLANT_NORMAL]
(x_bearing, y_bearing, text_width, text_height,
 x_advance, y_advance) = text_extent(font, font_size, text, *font_args)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(text_width), int(text_height))
ctx = cairo.Context(surface)
ctx.select_font_face(font, *font_args)
ctx.set_font_size(font_size)
ctx.move_to(-x_bearing, -y_bearing)
ctx.text_path(text)
ctx.set_source_rgb(0.47, 0.47, 0.47)
ctx.fill_preserve()
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(1.5)
ctx.stroke()

surface.write_to_png("/tmp/out.png")

Do I need to know the dimensions of the text to use this?

I can get the needed info with Context.text_extents("Example") but after that I need to create a new surface with the correct width and height.

Yes, unfortunately, I do not know a better way.

How can I draw text with different stroke and fill colors on images wi...

python image python-imaging-library
Rectangle 27 0

PIL font's do have a getsize method which you can use to get width and height of font, did you try that? e.g.

from PIL import Image, ImageDraw, ImageFont

fontFile = "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"
font = ImageFont.truetype(fontFile, 10)
text="anurag"
print font.getsize(text)
assert font.getsize(text)[0]*2 == font.getsize(text*2)[0]

python - draw text to center of the image using PIL - Stack Overflow

python text python-imaging-library
Rectangle 27 0

you concatenate everything into v. You should pull the drawing/printing function (txt2img(v)) in your loop.

for j in range(0,2):
    v = ("%s (%s%%)\n") % (career_list[j], ran_list[j])
    txt2img(v)

Thanks! But what i want is just draw one time. :)

@Chelsea_cole: Sometimes, you can't do exactly what you want; you have to do it the way that works with the software.

string - How to draw text with line breaks using Python's PIL - Stack ...

python string python-imaging-library line-breaks
Rectangle 27 0

There is no txt2img function in PIL. I used "Google" and it looks like you took the code from Koders.com. Anyway try this answer

string - How to draw text with line breaks using Python's PIL - Stack ...

python string python-imaging-library line-breaks
Rectangle 27 0

I'll try to clarify the procedure. At first What I did was use the "name" of the font like this

but only got some errors like this:

Traceback (most recent call last):
  File "C:/Users/555STi/PycharmProjects/PIL/img.py", line 8, in <module>
    font = ImageFont.truetype("C:\Windows\Fonts\Arial negrita.ttf",25)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 262, in truetype
    return FreeTypeFont(font, size, index, encoding)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 142, in __init__
    self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource

Then I remembered that sometimes fonts has other "names" or "filenames", so, what I did was going to fonts folder, then opened the Arial Font wich displayed all the styles like negrita (bold], cursiva(italic), etc.

Did a right click on the "negrita" style, selected "properties" and then there was the "real name" of the font.

In my case, the name was "ariblk"

Then, finally, just used the name like this.

font = ImageFont.truetype("C:\Windows\Fonts\\ariblk.ttf",25)

I know this post is old, but today helped me to get to the solution. So I hope to help anybody.

@Nilambar, what do you mean?. Sorry, I'm kinda new around here.

python - Draw bold/italic text with PIL? - Stack Overflow

python text fonts python-imaging-library draw
Rectangle 27 0

I ran across this error and I believe it is because your installed PIL was compiled without libfreetype. To get this you'd have to install freetype2 and then compile PIL. See

Alternatively you could try Pillow, which is an updated fork of the PIL library

python - Font Error When Drawing Text to an Image - Stack Overflow

python fonts python-imaging-library
Rectangle 27 0

Sounds like PIL was built without FreeType support. Install the FreeType dev files and rebuild PIL again.

Drawing Hebrew text to and image using Image module (python) - Stack O...

python image hebrew bidirectional
Rectangle 27 0

It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text).

(...)
img_main = Image.new("RGB", (200, 200))
font = ImageFont.load_default()

# Text to be rotated...
rotate_text = u'This text should be rotated.'

# Image for text to be rotated
img_txt = Image.new('L', font.getsize(rotate_text))
draw_txt = ImageDraw.Draw(img_txt)
draw_txt.text((0,0), rotate_text, font=font, fill=255)
t = img_value_axis.rotate(90, expand=1)

The rest of joining the two images together is already described on this page. When you rotate by an "unregular" angle, you have to improve this code a little bit. It actually works for 90, 180, 270...

How do I draw text at an angle using python's PIL? - Stack Overflow

python python-imaging-library imaging
Rectangle 27 0

import subprocess
import shlex

args={
    'bgColor':'transparent',
    'fgColor':'light slate grey',
    'fgOutlineColor':'red',
    'text':'Example',
    'size':72,
    'geometry':'350x100!',
    'output':'/tmp/out.png',
    'font':'helvetica'
    }

cmd='''convert
       xc:{bgColor!r} -resize {geometry} -gravity "Center" -font {font}
       -pointsize {size!r} -fill {fgColor!r} -stroke {fgOutlineColor!r}
       -draw "text 0,0 {text!r}" -trim {output!r}'''.format(**args)

proc=subprocess.Popen(shlex.split(cmd))
proc.communicate()

Do I need to know the dimensions of the output text before I can create it?

You may use any geometry you wish -- imagemagick will create an image of exactly that geometry as long as you use the exclamation point -- but if the font size is too large, part of the text may be cropped off.

I would like to get a picture that is the exact size of the text. No cropped text and no extra space on some side.

You can crop to the size of the text using the -trim option.

How can I draw text with different stroke and fill colors on images wi...

python image python-imaging-library
Rectangle 27 0

Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now.

This demo writes yellow text on a slant over an image:

# Demo to add rotated text to an image using PIL

import Image
import ImageFont, ImageDraw, ImageOps

im=Image.open("stormy100.jpg")

f = ImageFont.load_default()
txt=Image.new('L', (500,50))
d = ImageDraw.Draw(txt)
d.text( (0, 0), "Someplace Near Boulder",  font=f, fill=255)
w=txt.rotate(17.5,  expand=1)

im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60),  w)

How do I draw text at an angle using python's PIL? - Stack Overflow

python python-imaging-library imaging