Python implements circular image processing, Pillow


foreword

A few days ago, a poster generation function was implemented in the project, in which the user's avatar needs to be implemented in a circular display style.

Try to develop a piece of code in Python to achieve it.


1. Technical points

The development environment uses Python's own IDE.

1.1 Install the development kit

The Python package for image processing is, Pillow. If not installed, install the Pillow package first.
Pillow is an image processing library for Python, which can be used to open, manipulate and save various image formats, such as JPEG, PNG, BMP, GIF, etc. Pillow includes rich image processing functions, such as resizing, rotating, cropping, filter application, color adjustment, text drawing and so on. Pillow is a fork of the Python Imaging Library (PIL) that offers better performance and extensive support.

pip install Pillow

1.2 Import module

Introducing Pillow in the Python environment

import PIL
from PIL import Image, ImageDraw, ImageFont

1.2.1 Image module of Pillow

The Image module of Pillow is one of the core modules for processing images, and its main function is to open, manipulate and save images. The Image module supports multiple file formats, such as JPEG, PNG, BMP, GIF, etc., and provides rich image processing functions, including resizing, rotating, cropping, thumbnailing, filter application, color adjustment, text drawing, etc. By using the Image module, various processing and operations on images can be easily realized to meet the needs of different scenarios.

1.2.2 Pillow的ImageDraw

Pillow's ImageDraw module is one of the modules for drawing 2D graphics on images. Its main function is to create and edit various 2D shapes on images, such as lines, rectangles, ellipses, polygons, etc. To use the ImageDraw module, you need to create an ImageDraw object first, and provide parameters including the coordinates, color, width, etc. of the graphics, and then you can use the object to draw the image.

The ImageDraw module not only provides basic drawing functions, but also supports various text processing functions, such as adding text on images, adjusting fonts, colors and sizes, etc. By using the ImageDraw module, various 2D graphic drawing and text processing of images can be easily realized, so as to meet the needs of different scenarios.

1.2.3 Pillow's ImageFont

Pillow's ImageFont module is one of the modules used to manipulate and load fonts. Its main function is to provide support for different font files and allow parameters such as font, size, and color to be specified when adding text to images.

To use the ImageFont module, you need to load the corresponding font file and create a font object, and then you can pass the font object to the drawing function in the ImageDraw module to add the text of the specified font on the image.

The ImageFont module supports multiple font formats, such as TrueType (.ttf), OpenType (.otf), etc., and provides various font-related attributes, such as font name, size, style, etc. By using the ImageFont module, texts of various font types and styles can be added to images to meet the needs of different scenarios.

2. Requirements description

Generate a poster with a width of 600 and a length of 900. At the bottom of the poster, the program is automatically generated based on the user's information. The avatar is displayed on the left, and the avatar is displayed in a circle, followed by the user's name. A QR code is displayed on the right for users to scan the code. The main body is a designed poster.

The overall style is as follows:
Let's play AI poster base map

2.1 Detailed design (distance unit is unified as pixel)

The avatar is 50 from the left edge, 723 from the upper edge, the size of the avatar is 64 64,
the name is 129 from the left edge, 740 from the upper edge, and the text uses size 8. The QR
code is 407 from the left edge, 683 from the upper edge, and the size is 142
142

Other required content (Ignore 10000 words

All other content is basemap.

3. Technical realization

3.1 Define variable parameters

variable parameter

3.2 Structural Design

Write two functions named: CircleImage, GetPoster

3.2.1 CircleImage

Function: CircleImage(img)
Input parameters:

  • img a square image

return value:

  • An Image object processed into a circle

Function:

  • Process the image into a circle whose diameter is equal to the minimum side length of the input image

3.2.2 GetPoster

Function: GetPoster(c,h,n)
Input parameters:

  • c: QR code path
  • h: avatar path
  • n: username

return value:

  • Generated a poster image, Image object

Function:

  • Draw the QR code, avatar, and user name on the poster base map

3.3 Encoding

3.3.1 CircleImage

def CircleImage(img):
	# 重设尺寸为头像设计尺寸
	Img1 = img.resize(head_sz)
	
	# 将图像转换成RGBA模式。使用图像透明通道。
    img1 = img1.convert("RGBA")
    w, h = img1.size
    
	# 定义alpha通道
    alpha = Image.new("L", img1.size, color=0)
    draw = ImageDraw.Draw(alpha)

    # 绘制一个圆,填充为255,即白色
    draw.ellipse((0,0,w,h),fill=255)

    #应用透明通道到图片上
    img1.putalpha(alpha)
    
    return img1

3.3.2 GetPoster

def GetPoster(c,h,n):
    '''
      c  二维码图片
      h  头像图片
      n  名称
    '''

	# 读取海报底图
	o_poster = Image.open(Img_poster_base)
	o_poster = img_poster.convert("RGBA")
	    
	# 读取二维码图
	o_qr= Image.open(c)
	o_qr= o_qr.convert("RGBA")
	o_qr= o_qr.resize(qr_sz)
	
	# 读取头像图
	o_head = Image.open(h)
	o_head = img_head.resize(hd_sz)
	# 裁剪图像为圆形
	o_head = CircleImage(o_head)
	    
	# 将二维码贴到海报上
	o_poster.paste(o_qr, qr_xy)
	# 将头像贴到海报上 注意这里需要设置mask为目标图片的alpha
	o_poster.paste(o_head, hd_xy, mask=o_head.split()[-1])
	    
	draw = ImageDraw.Draw(o_poster)
	# 配置字体msyh.ttc是“微软雅黑”
	font = ImageFont.truetype('C:\Windows\Fonts\msyh.ttc', 18)
	# 写文字
	draw.text(name_xy, n, fill='white', font=font)
	# draw.text(textXY2, "邀请您一起来玩AI", fill='white', font=font)

    # 生成海报名称
    poster_name = "static/posters/POSTER_%s.png" % uuid.uuid4()
    # 保存海报
    o_poster.save(poster_name)

    # 显示海报
    o_poster.show()

    return poster_name

4. Display effect

4.1 Execution Results

insert image description here

4.2 Source code

Please use the following address to experience ChatGPT
https://www.zhiyidata.cn/chatgpt/play

Source code download

Guess you like

Origin blog.csdn.net/all_night_in/article/details/130556537