How to print pil image python (hardcopy)? - python

from PIL import Image, ImageDraw, ImageFont
import os
img = Image.new('RGB', (100, 30), color = (73, 109, 137))
#fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15)
d = ImageDraw.Draw(img)
d.text((10,10), "Hello world", fill=(255, 255, 0))
#img.save('pil_text_font.png')
I want to print this image on paper. How can I do that?
I tried,
os.startfile(img,'print')
Error:
TypeError: startfile: filepath should be string, bytes or os.PathLike, not Image

Save your image to a file then output to screen like so:
from PIL import Image, ImageDraw, ImageFont
img = Image.new('RGB', (100, 30), color = (73, 109, 137))
#fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15)
d = ImageDraw.Draw(img)
d.text((10,10), "Hello world", fill=(255, 255, 0))
img.save('pil_text_font.png')
# open method used to open different extension image file
im = Image.open(r"pil_text_font.png")
# This method will show image in any image viewer
im.show()
#delete the file immediately after to save space
os.remove("pil_text_font.png")
Here is a link on where I got my information from for this answer: https://www.geeksforgeeks.org/python-pil-image-open-method/

Related

PIL Writing Text on Image Using Escape Sequence

`from PIL import Image, ImageDraw, ImageFont
image = Image.new('RGB', (950, 250), color=(255, 255, 255))
TEXT = 'You are a wondeful \033[32mperson.'
font_size = 50
font_type = "SourceCodePro-Bold.ttf"
draw = ImageDraw.Draw(im=image)
font = ImageFont.truetype(font_type, font_size)
draw.multiline_text((int(950 / 2), int(250 / 2)), text=TEXT, font=font,fill=(0, 0, 0), anchor='mm')
image.show()`
I tried to print text on an image using some escape sequence "\033[32m" using PIL (Pillow).
I was expecting the below output image
What I want
What I'm getting
So anybody have any idea that how to get the desired result then it'll be very helpful.
Thanks.
You can try this one and change the position of text. i think this logic will help you. thanks
from PIL import Image, ImageDraw, ImageFont
image = Image.new('RGB', (950, 250), "white")
text1 = "You are a wondeful"
text2="Person"
font_size = 100
font_type = "SourceCodePro-Bold.ttf"
draw = ImageDraw.Draw(im=image)
font = ImageFont.load_default()
draw.multiline_text((int(950 / 2), int(250 / 2)), text=text1, font=font,fill ="black",anchor='mm')
draw.multiline_text((int(1180 / 2), int(250 / 2)), text=text2, font=font,fill = "green",anchor='mm')
image.show()

Create a PNG and make it transparent

I'm trying to dynamically create a PNG (code is working) and make it transparent (code is not working on the color white).
I can create the PNG, but making it transparent isn't working.
Code:
from PIL import Image, ImageDraw, ImageFont
import os
def text_on_img(filename='01.png', text="Hello", size=12):
"Draw a text on an Image, saves it, show it"
fnt = ImageFont.truetype('arial.ttf', 52)
# create image
image = Image.new(mode="RGB", size=(150, 75), color="white")
draw = ImageDraw.Draw(image)
# draw text
draw.text((10, 10), text, font=fnt, fill=(0, 0, 0))
newData = []
newData.append((255, 255, 255, 0))
image.save(filename)
Here's a minimal example that creates the image in RGBA mode and sets the background to be transparent.
from PIL import Image, ImageDraw, ImageFont
fnt = ImageFont.truetype("arial.ttf", 52)
img = Image.new(mode="RGBA", size=(150, 75), color=(255, 255, 255, 127))
draw = ImageDraw.Draw(img)
draw.text((10, 10), "Hello", font=fnt, fill=(0, 0, 0))
img.save("test.png", "PNG")
This creates the following image:
Changing the alpha to 127 (50%) results in the following image being created:

Pillow ImageDraw.Draw.textsize throws 'str' object has no attribute 'getsize'

In Pillow, I'm trying to get the size of a text so I could know how to place it in the image. When trying to do the following, I keep getting the error "AttributeError: 'str' object has no attribute 'getsize'" when calling d.textsize(text, font=font_mono).
What am I doing wrong?
from PIL import Image, ImageDraw
txt_img = Image.new("RGBA", (320, 240), (255,255,255,0)) # make a blank image for the text, initialized to transparent text color
d = ImageDraw.Draw(txt_img)
text = "abcabc"
font_mono="Pillow/Tests/fonts/FreeMono.ttf"
font_color_green = (0,255,0,255)
txt_width, _ = d.textsize(text, font=font_mono)
The font needs to be an ImageFont object:
from PIL import Image, ImageDraw, ImageFont
txt_img = Image.new("RGBA", (320, 240), (255,255,255,0))
d = ImageDraw.Draw(txt_img)
text = "abcabc"
font_mono="Pillow/Tests/fonts/FreeMono.ttf"
font_color_green = (0,255,0,255)
font = ImageFont.truetype(font_mono, 28)
txt_width, _ = d.textsize(text, font=font)

How to draw Chinese text on the image using `cv2.putText`correctly? (Python+OpenCV)

I use python OpenCV (Windows 10, Python 2.7) to write text in image, when the text is English it works, but when I use Chinese text it write messy code in the image.
Below is my code:
# coding=utf-8
import cv2
import numpy as np
text = "Hello world" # just work
# text = "内容理解团队" # messy text in the image
cv2.putText(img, text,
cord,
font,
fontScale,
fontColor,
lineType)
# Display the image
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
When text = "Hello world" # just work, below is the output image:
When text = "内容理解团队" # Chinese text, draw messy text in the image, below is the output image:
What's wrong? Does opencv putText don't support other language text?
The cv2.putText don't support no-ascii char in my knowledge. Try to use PIL to draw NO-ASCII(such Chinese) on the image.
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import cv2
import time
## Make canvas and set the color
img = np.zeros((200,400,3),np.uint8)
b,g,r,a = 0,255,0,0
## Use cv2.FONT_HERSHEY_XXX to write English.
text = time.strftime("%Y/%m/%d %H:%M:%S %Z", time.localtime())
cv2.putText(img, text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (b,g,r), 1, cv2.LINE_AA)
## Use simsum.ttc to write Chinese.
fontpath = "./simsun.ttc" # <== 这里是宋体路径
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80), "端午节就要到了。。。", font = font, fill = (b, g, r, a))
img = np.array(img_pil)
cv2.putText(img, "--- by Silencer", (200,150), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (b,g,r), 1, cv2.LINE_AA)
## Display
cv2.imshow("res", img);cv2.waitKey();cv2.destroyAllWindows()
#cv2.imwrite("res.png", img)
Refer to my another answer:
Load TrueType Font to OpenCV
According to this opencv forum, putText is only able to support a small ascii subset of characters and does not support unicode characters which are other symboles like chinese and arabic characters.
However, you can try to use PIL instead and follow the answer posted here and see if it works out for you.
Quick Start
np_img = np.ones((64, 32, 3), dtype=np.uint8) * 255 # background with white color
draw_text = init_parameters(cv2_img_add_text, text_size=32, text_rgb_color=(0, 0, 255), font='kaiu.ttf', replace=True)
draw_text(np_img, '您', (0, 0))
draw_text(np_img, '好', (0, 32))
cv2.imshow('demo', np_img), cv2.waitKey(0)
what is init_parameters() and cv2_img_add_text()?
see as below:
EXAMPLE
from typing import Tuple
import numpy as np
import cv2
from PIL import Image, ImageDraw, ImageFont
# define decorator
def init_parameters(fun, **init_dict):
"""
help you to set the parameters in one's habits
"""
def job(*args, **option):
option.update(init_dict)
return fun(*args, **option)
return job
def cv2_img_add_text(img, text, left_corner: Tuple[int, int],
text_rgb_color=(255, 0, 0), text_size=24, font='mingliu.ttc', **option):
"""
USAGE:
cv2_img_add_text(img, '中文', (0, 0), text_rgb_color=(0, 255, 0), text_size=12, font='mingliu.ttc')
"""
pil_img = img
if isinstance(pil_img, np.ndarray):
pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(pil_img)
font_text = ImageFont.truetype(font=font, size=text_size, encoding=option.get('encoding', 'utf-8'))
draw.text(left_corner, text, text_rgb_color, font=font_text)
cv2_img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)
if option.get('replace'):
img[:] = cv2_img[:]
return None
return cv2_img
def main():
np_img = np.ones(IMG_SHAPE, dtype=np.uint8) * 255 # background with white color
np_img = cv2_img_add_text(np_img, 'Hello\nWorld', (0, 0), text_rgb_color=(255, 0, 0), text_size=TEXT_SIZE)
np_img = cv2_img_add_text(np_img, '中文', (0, LINE_HEIGHT * 2), text_rgb_color=(0, 255, 0), text_size=TEXT_SIZE)
cur_y = LINE_HEIGHT * 3
draw_text = init_parameters(cv2_img_add_text, text_size=TEXT_SIZE, text_rgb_color=(0, 128, 255), font='kaiu.ttf', replace=True)
for msg in ('笑傲江湖', '滄海一聲笑'):
draw_text(np_img, msg, (0, cur_y))
cur_y += LINE_HEIGHT + 1
draw_text(np_img,
"""123
456
789
""", (0, cur_y))
cv2.imshow('demo', np_img), cv2.waitKey(0)
if __name__ == '__main__':
IMG_HEIGHT, IMG_WIDTH, CHANNEL = IMG_SHAPE = (250, 160, 3)
TEXT_SIZE = LINE_HEIGHT = 32
main()

How to convert a string to an image?

I started to learn python a week ago and want to write a small program that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails.
It seems like the python standard library doesn't contain a module that can do that but I've found out that there's a PIL module for it (PIL.ImageDraw).
My problem is that I can't seem to get it working.
So basically my questions are:
How to draw a text onto a image.
How to create a blank (white) image
Is there a way to do this without actually creating a file so that I can show it in a GUI before saving it?
Current Code:
import Image
import ImageDraw
import ImageFont
def getSize(txt, font):
testImg = Image.new('RGB', (1, 1))
testDraw = ImageDraw.Draw(testImg)
return testDraw.textsize(txt, font)
if __name__ == '__main__':
fontname = "Arial.ttf"
fontsize = 11
text = "example#gmail.com"
colorText = "black"
colorOutline = "red"
colorBackground = "white"
font = ImageFont.truetype(fontname, fontsize)
width, height = getSize(text, font)
img = Image.new('RGB', (width+4, height+4), colorBackground)
d = ImageDraw.Draw(img)
d.text((2, height/2), text, fill=colorText, font=font)
d.rectangle((0, 0, width+3, height+3), outline=colorOutline)
img.save("D:/image.png")
use ImageDraw.text - but it doesn't do any formating, it just prints string at the given location
img = Image.new('RGB', (200, 100))
d = ImageDraw.Draw(img)
d.text((20, 20), 'Hello', fill=(255, 0, 0))
to find out the text size:
text_width, text_height = d.textsize('Hello')
When creating image, add an aditional argument with the required color (white):
img = Image.new('RGB', (200, 100), (255, 255, 255))
until you save the image with Image.save method, there would be no file. Then it's only a matter of a proper transformation to put it into your GUI's format for display. This can be done by encoding the image into an in-memory image file:
import cStringIO
s = cStringIO.StringIO()
img.save(s, 'png')
in_memory_file = s.getvalue()
or if you use python3:
import io
s = io.BytesIO()
img.save(s, 'png')
in_memory_file = s.getvalue()
this can be then send to GUI. Or you can send direct raw bitmap data:
raw_img_data = img.tostring()
The first 3 lines are not complete, when I'm not wrong. The correct code would be:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

Categories