Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating PIL Image does not seem to rotate canvas (no TKinter canvas added)

I'm having an issue rotating an image I've created. Because the code is spread out amongst a number of methods, I have put what I think to be the pertinent commands below.

The issue is that while the image is created successfully, when I rotate it using the img.rotate(-90)...the image rotates, but it appears the pallet/background/canvas does not (see attached image).

How can I correct this. Do I need to create a larger transparent background? Can I get the background/canvas to rotate as well...or do I rotate and then resize the background/Canvas?

FIRST EXAMPLE IMAGE (QRCODE)

img = Image.new('RGB', (x,y), 'white')
qr = qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=10,border=1,)
qr.add_data('QRB.NO/AbCd1')
qr.make(fit=True)
QRimg = qr.make_image()
img = img.paste(QRimg, (x,y))
img.show() #333
raw_input('(Above is unrotated QRcode image) Press enter...') #333
img = img.rotate(-90)
print img, type(img)
img.show() #333
raw_input('Above is the rotated -90 QRcode image. Press enter...') #333

SECOND EXAMPLE IMAGE

font_name      = 'Arial.ttf'
font_size      = 16 
font = ImageFont.truetype(font_name, font_size)
img = Image.new('RGB', (x,y), color=background_color)
# Place text 
draw = ImageDraw.Draw(img)
draw.text( (corner_X,corner_Y), 'QRB.NO/AbCd1', font=font, fill='#000000' ) 
draw.rectangle((0,0,x-1,y-1), outline = "black")
del draw
print img, type(img)
img.show() #333
raw_input('(Above is the unrotated test image). Press enter...') #333
img = img.rotate(90)
print img, type(img)
img.show() #333
raw_input('(Above is the ROTATED 90 text image). Press enter...') #333

OUTPUT

<PIL.Image.Image image mode=RGB size=71x57 at 0x10E9B8C10> <class 'PIL.Image.Image'>
(Above is unrotated QRcode image) Press enter...

<PIL.Image.Image image mode=RGB size=71x57 at 0x10E9B8F90> <class 'PIL.Image.Image'>
Above is the rotated -90 QRcode image. Press enter...

<PIL.Image.Image image mode=RGB size=57x9 at 0x10EA6CB90> <class 'PIL.Image.Image'>
(Above is the unrotated test image). Press enter...

<PIL.Image.Image image mode=RGB size=57x9 at 0x10E9B8C10> <class 'PIL.Image.Image'>
(Above is the ROTATED 90 text image). Press enter...


Bad Rotations

EDIT:

x,y = img.size
img = img.resize( (y, x),  Image.ANTIALIAS )
img = img.rotate(-90)

...or...

x,y = img.size
img = img.rotate(-90)
img = img.resize( (y, x),  Image.ANTIALIAS )

...don't seem to help.

Trying resize and rotate

like image 228
RightmireM Avatar asked Mar 10 '16 10:03

RightmireM


1 Answers

Figured it out. I'm going to leave it up to help others, as this seems to be a subtle yet important difference.

img = img.transpose(Image.ROTATE_270) 

...or...

img = img.transpose(Image.ROTATE_90) 

Docs

like image 59
RightmireM Avatar answered Sep 23 '22 11:09

RightmireM