05. The last task --- generate photo wall

A learning knowledge python anonymous function (lambda expression)

See python based tutorial

Learn a function point

from PIL import Image

im = Image.open('35.jpg').convert('RGBA')
_, _, _, alpha = im.split()
alpha = alpha.point(lambda i: 150)
im.putalpha(alpha)

im.save('luozi.png')

ready

1. font files demo.ttf
link: https://pan.baidu.com/s/1wLKMd0VoO7C5jCAAfpjBEw
extraction code: ub9l
New Folder 2 out under the project directory, store the final-generated image

Code:

from PIL import Image, ImageDraw, ImageFont
import os

def gen_text_img(text, font_size=20, font_path=None):
    # 从文字生成图像,输入:文字内容,文字字体大小,字体路径
    font = ImageFont.truetype(font_path, font_size) if font_path is not None else None
    (width, length) = font.getsize(text)  # 获取文字大小
    text_img = Image.new('RGBA', (width, length))
    draw = ImageDraw.Draw(text_img)
    # 第一个tuple表示未知(left,up),之后是文字,然后颜色,最后设置字体
    draw.text((0, 0), text, fill=(0, 0, 0), font=font)
    text_img.save('testtext.png')
    return text_img

def trans_alpha(img, pixel):
    '''根据rgba的pixel调节img的透明度
    这里传进来的pixel是一个四元组(r,g,b,alpha)
    '''
    _, _, _, alpha = img.split()
    alpha = alpha.point(lambda i: pixel[-1]*10)
    img.putalpha(alpha)
    return img

def picture_wall_mask(text_img, edge_len, pic_dir="./user"):
    # 根据文字图像生成对应的照片墙,输入:文字图像,各个照片边长,照片所在路径
    new_img = Image.new('RGBA', (text_img.size[0] * edge_len, text_img.size[1] * edge_len))
    file_list = os.listdir(pic_dir)
    img_index = 0
    for x in range(0, text_img.size[0]):
        for y in range(0, text_img.size[1]):
            pixel = text_img.getpixel((x, y))
            file_name = file_list[img_index % len(file_list)]
            try:
                img = Image.open(os.path.join(pic_dir, file_name)).convert('RGBA')
                img = img.resize((edge_len, edge_len))
                img = trans_alpha(img, pixel)

                new_img.paste(img, (x * edge_len, y * edge_len))
                img_index += 1
            except Exception as e:
                print(f"open file {file_name} failed! {e}")
    return new_img


def main(text='', font_size = 20, edge_len = 60,pic_dir = "./user", out_dir = "./out/", font_path = './demo.ttf'):

    '''生成照片墙

    :param text: Text of picture wall, if not defined this will generage a rectangle picture wall
    :param font_size: font size of a clear value
    :param edge_len: sub picture's egde length

    '''

    if len(text) >= 1:
        text_ = ' '.join(text)#将字符串用空格分隔开
        print(f"generate text wall for '{text_}' with picture path:{pic_dir}")

        text_img = gen_text_img(text_, font_size, font_path)
        # text_img.show()
        img_ascii = picture_wall_mask(text_img, edge_len, pic_dir)
        # img_ascii.show()
        img_ascii.save(out_dir + os.path.sep + '_'.join(text) + '.png')

if __name__ == '__main__':
    main(text='东软')

Code principle:

1.gen_text_img function generates an image (including the character set) according to the character set and font size, as shown below:

468490-4292553cdfac4b7b.png
image.png

Generating a first image (above) with a given string, and the width extending edge_len times for each pixel of the picture, but also the high expansion fold edge_len assumed edge_len = 60, then the text of the original image (above) of each pixel becomes 60 * 60 pixels of a picture (we'll each group of friends head into them); different transparency for each pixel of the original text images, such as displaying local Neusoft these two words, low transparency (opaque), these two words surrounding areas, high transparency (transparency), according to the transparency of our original text and graphics for each pixel, set into the pixel (width and height in fact had expanded 60-fold) the position of the micro-letter friends transparency avatar (trans_alpha method implementation).

final effect

468490-d9ca718c3a27e3ad.png
image.png

Guess you like

Origin blog.csdn.net/weixin_34380296/article/details/90997892