PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

preface

There are only 19 days left before the Chinese New Year. Happy New Year to all of you

First of all, an aside: the epidemic is still quite serious. If you go out, you must take protective measures. If you don’t go out, it’s best.

It’s not easy for everyone, and it’s not helpful if you’re not a professional, but at least don’t make things worse. A lot of things on the Internet test IQ, I hope you have the ability to distinguish right from wrong, read more official reports, at least more reliable than those things.

OK, the Chinese New Year is coming. I wrote a New Year card generator to share with you. Happy New Year to you all.

Let’s have a good time

The development tools

Python version: 3.6.4

Related modules:

OS module;

IO module;

Sys module;

Pillow module;

Pyqt5 module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules. Happy New Year to you all

The idea behind creating a greeting card generator is simple. First, find some festive background images:

Write on these background images using the Pillow module

Generate greeting card
def generate(self) :
    Check whether the path exists
    content_path = self.content_edit.text()
    bg_path = self.bg_edit.text()
    font_path = self.font_edit.text()
    font_color = self.font_color_combobox.currentText()
    if (not self.checkFilepath(content_path)) or (not self.checkFilepath(bg_path)) or (not self.checkFilepath(font_path)):
        self.card_image = None
        return False
    # write a greeting card
    contents = open(content_path, encoding='utf-8').read().split('\n')
    font_card = ImageFont.truetype(font_path, self.font_size)
    image = Image.open(bg_path).convert('RGB')
    draw = ImageDraw.Draw(image)
    draw.text((180.30), contents[0], font=font_card, fill=font_color)
    for idx, content in enumerate(contents[1: -1]):
        draw.text((220.40+(idx+1) *40), content, font=font_card, fill=font_color)
    draw.text((180.40+(idx+2) *40+10), contents[-1], font=font_card, fill=font_color)
    # show
    fp = io.BytesIO()
    image.save(fp, 'BMP')
    qtimg = QtGui.QImage()
    qtimg.loadFromData(fp.getvalue(), 'BMP')
    qtimg_pixmap = QtGui.QPixmap.fromImage(qtimg)
    self.show_label.setPixmap(qtimg_pixmap)
    self.card_image = image
Copy the code

For good effect, make a GUI with PyQt5:

The content path is the text file with the message:

I don’t have to explain the rest of it because you can understand it. Completed, complete source code see related files ~