Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for generating equal diagonal lines in PIL

$
0
0

You can do it by first generating an image of vertical lines like I showed you in my answer to your other question, rotating that by 45°, and then cropping it. To avoid having areas of black, you need to generate an initial image that is large enough for the cropping.

In this case that's simply a square image with sides the length of the hypotenuse (diagonal) of the final target image's size.

hypotenuse

i.e. formula

Graphically, here's what I mean:

uncropped image

At any rate, here's the code that does it:

from math import hypotfrom PIL import Image, ImageDrawimport randomIMG_WIDTH, IMG_HEIGHT = 1000, 1000DIAG = round(hypot(IMG_WIDTH, IMG_HEIGHT))img = Image.new('RGB', (DIAG, DIAG), (255, 255, 255))draw = ImageDraw.Draw(img)colors = [(255,0,255), (0,0,255)]random.shuffle(colors)length = len(colors)  # Number of lines.line_width = DIAG / length  # Width of each.difx = line_width / 2x1, y1 = difx, 0x2, y2 = difx, DIAGfor color in colors:    endpoints = (x1, y1), (x2, y2)    draw.line(endpoints, fill=color, width=round(line_width))    x1 += line_width    x2 += line_widthimg = img.rotate(-45, resample=Image.Resampling.BICUBIC)difx, dify = (DIAG-IMG_WIDTH) // 2, (DIAG-IMG_HEIGHT) // 2img = img.crop((difx, dify, difx+IMG_WIDTH, dify+IMG_HEIGHT))img.save('diagonal.png')#img.show()

Here's the resulting image:

diagonal image


Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>