- Python Multimedia
- Ninad Sathaye
- 355字
- 2021-08-03 15:27:39
Time for action – creating a new image containing some text
As already stated, it is often useful to generate an image containing only some text or a common shape. Such an image can then be pasted onto another image at a desired angle and location. We will now create an image with text that reads, "Not really a fancy text!"
- Write the following code in a Python source file:
1 import Image 2 import ImageDraw 3 txt = "Not really a fancy text!" 4 size = (150, 50) 5 color = (0, 100, 0) 6 img = Image.new('RGB', size, color) 7 imgDrawer = ImageDraw.Draw(img) 8 imgDrawer.text((5, 20), txt)9 img.show()
- Let's analyze the code line by line. The first two lines import the necessary modules from PIL. The variable
txt
is the text we want to include in the image. On line 7, the new image is created usingImage.new
. Here we specify themode
andsize
arguments. The optionalcolor
argument is specified as atuple
with RGB values pertaining to the "dark green" color. - The
ImageDraw
module in PIL provides graphics support for anImage
object. The functionImageDraw.Draw
takes an image object as an argument to create aDraw
instance. In output code, it is calledimgDrawer
, as used on line 7. ThisDraw
instance enables drawing various things in the given image. - On line 8, we call the text method of the Draw instance and supply position (a
tuple
) and the text (stored in the stringtxt
) as arguments. - Finally, the image can be viewed using
img.show()
call. You can optionally save the image usingImage.save
method. The following screenshot shows the resultant image.
What just happened?
We just learned how to create an image from scratch. An empty image was created using the Image.new
method. Then, we used the ImageDraw
module in PIL to add text to this image.
Reading images from archive
If the image is part of an archived container, for example, a TAR archive, we can use the TarIO
module in PIL to open it and then call Image.open
to pass this TarIO
instance as an argument.
推薦閱讀
- AutoCAD 2022快速入門、進階與精通
- IBM Rational ClearCase 7.0: Master the Tools That Monitor, Analyze, and Manage Software Configurations
- 突破平面Premiere Pro 2022短視頻與視頻制作
- CorelDRAW服裝設計實用教程(第四版)
- 中文版CorelDRAW X6基礎培訓教程(第2版)
- 平面設計制作標準教程(微課版 第2版)
- Backbone.js Cookbook
- Power Query For Excel:讓工作化繁為簡
- 科技繪圖/科研論文圖/論文配圖設計與創作自學手冊:科研動畫篇
- Premiere Pro CC 2015中文版基礎與實例教程(第4版)
- NX Open API編程技術
- Cinema 4D基礎與實戰教程
- Cinema 4D基礎培訓教材
- JBoss Drools Business Rules
- Photoshop CS6圖像處理立體化教程