# How can I draw a circle in an image inside the image editor?

I would like to be able to draw a circle inside an image that is available in image editor.

I found this code here but I do not know how to manipulate the xy values for drawing a circle properly.

size = 640, 480

import bpy
# blank image
image = bpy.data.images.new("MyImage", width=size, height=size)

## For white image
# pixels = [1.0] * (4 * size * size)

pixels = [None] * size * size
for x in range(size):
for y in range(size):
# assign RGBA to something useful
r = x / size
g = y / size
b = (1 - r) * g
a = 1.0

pixels[(y * size) + x] = [r, g, b, a]

# flatten list
pixels = [chan for px in pixels for chan in px]

# assign pixels
image.pixels = pixels

# write image
image.filepath_raw = "/tmp/temp.png"
image.file_format = 'PNG'
image.save()

$$$$

• Wow never knew direct pixel access was possible. Can we now extend it with popular python image libraries as well? – Peter Jan 25 '20 at 11:24

Try this (I'm on Blender 2.81a):

import bpy
import math

size = 640, 480

# Calculate distance between two point
def distance(p0, p1):
return math.sqrt((p0 - p1)**2 + (p0 - p1)**2)

# blank image
image = bpy.data.images.new("circle_img", width=size, height=size)

pixels = [None] * size * size
center = (int(size/2.0), int(size/2.0)) # center of image
for x in range(size):
for y in range(size):
d = distance((x,y),center)
r = g = b = a = 1.0 # white
else:
r = g = b = 0.0 # black
a = 1.0
pixels[(y * size) + x] = [r, g, b, a]

# flatten list
pixels = [chan for px in pixels for chan in px]

# assign pixels
image.pixels = pixels

# write image
image.filepath_raw = "/tmp/temp.png"
image.file_format = 'PNG'
image.save()


Circle isn't very pretty though (could use some anti-alias or blur)!

• Thanks, that works for me. – yarun can Jan 14 '20 at 17:16
• Be tempted to leverage of v = Vector((x + 0.5, y + 0.5)) rather than the expensive euclidean distance calculation, and maybe use the "pixel center" (eg for pixel 0, 0 the center is (0.5, 0.5)) and not type cast the image center to int. The distance is then (v - center).length` – batFINGER Jan 15 '20 at 2:10