How to create your own Avatar using Python ?


Creating an avatar using Python can be done in several ways. Here are three methods:

Method 1: Using PIL (Python Imaging Library)

  • Install PIL using pip: pip install pillow
  • Create a new Python file and import the necessary libraries:
from PIL import Image, ImageDraw
  • Create a new image and draw a circle for the head:
img = Image.new('RGB', (300, 300), color = 'white')
draw = ImageDraw.Draw(img)
draw.ellipse((50, 50, 250, 250), fill='lightblue', outline='blue', width=10)
  • Draw the eyes, nose, and mouth:
draw.ellipse((100, 100, 125, 125), fill='black')
draw.ellipse((175, 100, 200, 125), fill='black')
draw.polygon([(125, 175), (150, 200), (175, 175)], fill='black')
  • Save the image:
img.save('avatar.png')

Method 2: Using PyCairo

  • Install PyCairo using pip: pip install pycairo
  • Create a new Python file and import the necessary libraries:
import cairo
  • Create a new image and draw a circle for the head:
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 300)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
ctx.arc(150, 150, 100, 0, 2 * 3.14)
ctx.set_source_rgb(0, 0, 1)
ctx.set_line_width(10)
ctx.stroke()
ctx.set_source_rgb(0.5, 0.5, 1)
ctx.fill()
  • Draw the eyes, nose, and mouth:
ctx.arc(110, 110, 10, 0, 2 * 3.14)
ctx.arc(190, 110, 10, 0, 2 * 3.14)
ctx.set_source_rgb(0, 0, 0)
ctx.fill()
ctx.move_to(130, 170)
ctx.line_to(150, 190)
ctx.line_to(170, 170)
ctx.set_line_width(10)
ctx.stroke()
  • Save the image:
surface.write_to_png('avatar.png')

Method 3: Using Turtle Graphics

  • Create a new Python file and import the necessary libraries:
import turtle
  • Create a new turtle and draw a circle for the head:
t = turtle.Turtle()
t.penup()
t.goto(0, -100)
t.pendown()
t.begin_fill()
t.fillcolor('lightblue')
t.circle(100)
t.end_fill()
  • Draw the eyes, nose, and mouth:
t.penup()
t.goto(-40, 20)
t.pendown()
t.begin_fill()
t.fillcolor('black')
t.circle(10)
t.end_fill()
t.penup()
t.goto(40, 20)
t.pendown()
t.begin_fill()
t.fillcolor('black')
t.circle(10)
t.end_fill()
t.penup()
t.goto(0, 0)
t.pendown()
t.pensize(10)
t.goto(-30, -30)
t.goto(30, -30)
t.penup()
t.goto(0, -50)
t.pendown()
t.goto(0, -70)
  • Save the image:
turtle.getcanvas().postscript(file='avatar.eps')

Note: You can convert the EPS file to PNG using an image editor or an online converter.

These are just a few examples of how to create an avatar using Python. There are many other libraries and methods you can use, depending on your preferences and requirements.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.