First, install PIL library in pytho3 has been called Pillow, installation command: pip install Pillow
But in the name of the application you want to import also called: PIL
In the digital image can be newly generated by the random number, so it needs to import a random
Then you can write code directly defined functions
Perform functions
The complete code
PIL Import Image from, ImageDraw, ImageFont, ImageColor
Import Random
DEF Put_Add_Num (PIC, NUM):
IM = Image.open (PIC) # open the picture
draw = ImageDraw.Draw (im) # create draw objects
x, y = im.size # get picture size
font = ImageFont.truetype ( "arial.ttf", 50) # set the font size
fillcolor = ImageColor.colormap.get ( "red") # set the font color
draw.text ((x - 30,40), "% s"% num, font = font, fill = fillcolor) # add text
im.save ( "D: \\ \\ Test_script image.png")
IF the __name__ == "__main__":
PIC = "D: \\ Test_script \\ Pic \\ WeChat.jpg "# image path
num = random.randint (1,10) # add random integer from 1 to 10
Put_Add_Num (pic, num)
finally stepped on to talk about the pit
1, save to save the image best to use png format, or if the original picture is png format will error: OSError: cannot write mode RGBA as JPEG
This is because: PNG RGBA there are four channels, while JPEG is RGB three channels, so when BMP PNG turn the channel does not know how to do A, will generate an error.
The best solution is to give up a channel saved as png format, or increase if the judge sentences
2, the escape character path to save the image of the original path and the new picture of needs: '\'
3, get a picture of coordinates PIl consistent starting coordinates for the upper-left corner of the picture (0,0)
4, hexadecimal color specifier, defined as "#rgb" or "#rrggbb". For example, "# ff0000" represents pure red
5, ImageDraw module provides 140 standard color name, Xwindow system and most web browsers support these colors. Color names are not case sensitive. For example, "red" and "Red" expressed pure red.