欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python-PIL模块画图

程序员文章站 2022-07-10 15:03:28
...

python中执行mysql遇到like 怎么办 ?

​sql = "SELECT * FROM T_ARTICLE WHERE title LIKE '%%%%%s%%%%'" % searchStr

执行成功,print出SQL语句之后为:

SELECT * FROM T_ARTICLE WHERE title LIKE '%%生活%%'

原因:
Python在执行sql语句的时候,同样也会有%格式化的问题,仍然需要使用%%来代替%。因此要保证在执行sql语句的时候格式化正确。而不只是在sql语句(字符串)的时候正确。

import Image, ImageDraw, ImageFont, ImageFilter

import random

随机字母

def rndChar():
return chr(random.randint(65, 90))

随机颜色1

def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

随机颜色2

def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

240 * 60

width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255,255,255))

创建Font对象

font = ImageFont.truetype('/usr/share/fonts-droid/truetype/DroidSansFallback.ttf', 36)

创建Draw对象

draw = ImageDraw.Draw(image)

填充每个像素

for x in range(width):
for y in range(height):
draw.point((x, y),fill=rndColor())

输出文字

for t in range(4):
draw.text((60 * t +10, 10), rndChar(), font=font, fill=rndColor2())

模糊

image = image.filter(ImageFilter.BLUR)

image.save('/home/godben/code.jpg', 'jpeg')

#!/usr/bin/env python
#coding=utf-8
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(3, 10))) # 数字

init_chars = ''.join((_letter_cases, _upper_cases, _numbers))

def create_validate_code(size=(120, 30),
chars=init_chars,
img_type="GIF",
mode="RGB",
bg_color=(255, 255, 255),
fg_color=(0, 0, 255),
font_size=18,
font_type="kk.TTF",
length=4,
draw_lines=True,
n_line=(1, 2),
draw_points=True,
point_chance = 2):
'''
@todo: 生成验证码图片
@param size: 图片的大小,格式(宽,高),默认为(120, 30)
@param chars: 允许的字符集合,格式字符串
@param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
@param mode: 图片模式,默认为RGB
@param bg_color: 背景颜色,默认为白色
@param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
@param font_size: 验证码字体大小
@param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
@param length: 验证码字符个数
@param draw_lines: 是否划干扰线
@param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
@param draw_points: 是否画干扰点
@param point_chance: 干扰点出现的概率,大小范围[0, 100]
@return: [0]: PIL Image实例
@return: [1]: 验证码图片中的字符串
'''
width, height = size # 宽, 高
img = Image.new(mode, size, bg_color) # 创建图形
draw = ImageDraw.Draw(img) # 创建画笔

def get_chars():
    '''生成给定长度的字符串,返回列表格式'''
    return random.sample(chars, length)

def create_lines():
    '''绘制干扰线'''
    line_num = random.randint(*n_line) # 干扰线条数
    for i in range(line_num):
        # 起始点
        begin = (random.randint(0, size[0]), random.randint(0, size[1]))
        #结束点
        end = (random.randint(0, size[0]), random.randint(0, size[1]))
        draw.line([begin, end], fill=(0, 0, 0))

def create_points():
    '''绘制干扰点'''
    chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]

    for w in xrange(width):
        for h in xrange(height):
            tmp = random.randint(0, 100)
            if tmp > 100 - chance:
                draw.point((w, h), fill=(0, 0, 0))

def create_strs():
    '''绘制验证码字符'''
    c_chars = get_chars()
    strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开

    font = ImageFont.truetype(font_type, font_size)
    font_width, font_height = font.getsize(strs)
    draw.text(((width - font_width) / 3, (height - font_height) / 3),
                strs, font=font, fill=fg_color)

    return ''.join(c_chars)
if draw_lines:
    create_lines()
if draw_points:
    create_points()
strs = create_strs()
# 图形扭曲参数
params = [1 - float(random.randint(1, 2)) / 100,
          0,
          0,
          0,
          1 - float(random.randint(1, 10)) / 100,
          float(random.randint(1, 2)) / 500,
          0.001,
          float(random.randint(1, 2)) / 500
          ]


img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)

return img, strs

if name == "main":
code_img = create_validate_code()
code_img[0].save("xiaorui.cc.gif", "GIF")

#coding:utf-8
#编写验证码
#随机的数值
#图片
import random #python随机模块
from PIL import Image #图片
from PIL import ImageDraw #画笔
from PIL import ImageFont #字体
from PIL import ImageFilter #滤镜 验证码扭曲

#验证码编写步骤

#1、定义随机数
sample_text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sample_list = random.sample(sample_text,4)
randomText = "".join(sample_list)

#2、定义图片
img = Image.new("RGB",(150,50),(255,255,255))
#第一个参数是配色方案
#第二个参数是图片的尺寸px 宽高
#第三个参数是颜色 255,255,255是白色

#3、图片上绘制干扰项

#实例化画笔
draw = ImageDraw.Draw(img)
#绘制干扰线
for i in range(random.randint(10,20)): #随机循环1-10次

draw.line(
    #两个点决定一条线
    #每个点有x,y两个值
    [
        (
            random.randint(1,150), # x
            random.randint(1,150), # y
        ),#点一

        (
            random.randint(1,150),  # x
            random.randint(1,150),  # y
        )#点二

    ],#一条线

    fill = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #线条颜色

) #绘制线条

#绘制点

for j in range(1000):
draw.point( 
​ [ random.randint(1, 150), # x
random.randint(1, 150), # y
],#一个点
fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 线条颜色

)

#4、书写文字
#定义字体

text = "".join(randomText)

font = ImageFont.truetype("simsun.ttc",36) #定义字体

draw.text((random.randint(1, 10),random.randint(1, 5)),text,font = font,fill = "green") #书写文字

#文字起始位置
#文字内容
#文字字体
#文字颜色

#5、进行滤镜扭曲
#定义扭曲的参数

params = [
1-float(random.randint(1,2))/100,
0,
0,
0,
1 - float(random.randint(1, 2)) / 100,
float(random.randint(1, 2)) / 100,
0.001,
float(random.randint(1, 2)) / 100
]

#使用滤镜
img = img.transform((150,50),Image.PERSPECTIVE,params)
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)

#6、查看效果
img.show() #展示
img.save("%s.jpg"%randomText,"JPEG") #保存,保存路径

生成随机验证码图片

import string
from random import randint, sample
from PIL import Image, ImageDraw, ImageFont, ImageFilter

Image 负责处理图片

ImageDraw 画笔

ImageFont 文字

ImageFileter 滤镜

定义变量

img_size = (150,50) # 定义画布大小
img_rgb = (255,255,255) # 定义画布颜色,白色
img = Image.new("RGB",img_size,img_rgb)

img_text = " ".join(sample(string.ascii_letters+string.digits, 5))

print(img_text.replace(' ',''))

画图

drow = ImageDraw.Draw(img)
for i in range(10):

随机画线

drow.line([tuple(sample(range(img_size[0]),2)), tuple(sample(range(img_size[0]),2))], fill=(0,0,0))

for i in range(99):

随机画点

drow.point(tuple(sample(range(img_size[0]),2)), fill=(0,0,0))

文字

font = ImageFont.truetype("simsun.ttc", 24) # 定义文字字体和大小
drow.text((6,6), img_text, font=font, fill="green")

扭曲图片和滤镜

params = [
1 - float(randint(1,2)) / 100,
0,
0,
0,
1 - float(randint(1,10)) /100,
float(randint(1,2)) / 500,
0.001,
float(randint(1,2)) / 500
]

img = im​g.transform(img_size, Image.PERSPECTIVE, params)

img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)

展示图片

img.show()

写一个理财计算器,实现将每日/月/年的利息进行复投进行计算

money = float(input('请输入您打算用来投资的本金 \> '))
year = int(input('请输入投资期限(单位:年) \> '))
rate = float(input('请输入投资年化收益率 \> '))
Type = int(input('''1.每日利息复投 2.每月利息复投 3.每年利息复投 请选择复投方式 \> '''))

def day_return(money,year,rate=0.12):
'方案:每日利息加入本金复投!'
for y in range(year):
for day in range(365):
money = money*rate/365 + money
print('第%d年结束时,本金为:%.2f' % (y+1,money))

def month_return(money,year,rate=0.12):
'方案:每月利息加入本金复投!'
for y in range(year):
for month in range(12):
money = money*rate/12 + money
print('第%d年结束时,本金为:%.2f' % (y+1,money))

def year_return(money,year,rate=0.12):
'方案:每年利息加入本金复投!'
for y in range(year):
money = money*rate + money
print('第%d年结束时,本金为:%.2f' % (y+1,money))

if Type == 1:
day_return(money,year,rate)
elif Type == 2:
month_return(money,year,rate)
elif Type == 3:
year_return(money,year,rate)
else:
print('输入有误!')

百度翻译

Python 3.5.1

from urllib import request, parse
import json

url = 'http://fanyi.baidu.com/v2transapi'
context = input('请输入需要翻译的内容 :\> ')

if context >= '\u4e00' and context <= '\u9fa5':

判断输入内容是否为汉字

From,To = 'zh','en'

else:
From,To = 'en','zh'

data = {
'query':context,
'from':From,
'to':To,
'transtype':'translang',
'simple_means_flag':3
}
data = parse.urlencode(data).encode('utf-8')

r = request.Request(url,data)
r.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0')
html = request.urlopen(r).read().decode('utf-8')
Result = json.loads(html)

print('翻译结果为:' + Result['trans_result']['data'][0]['dst'])

简单的拼手气红包

import random
from time import sleep

所有涉及金额的浮点数都需要用 round 方法保留2位小数,避免出现最终结果多出0.01

amount = round(float(input('请设置红包的金额 \> ')),2)
num = int(input('请设置红包的数量 \> '))
hb_dict = {}
xing = '赵钱孙李周吴郑王'
ming = '一二三四五六七八九十'

while num:

xingming = random.choice(xing)+random.choice(ming)+random.choice(ming)
if xingming in hb_dict.keys():
    xingming = random.choice(xing)+random.choice(ming)+random.choice(ming)

num -= 1
if num == 0:
    print('%s抢到红包%.2f元 红包抢完了!' % (xingming,amount))
    hb_dict[amount] = xingming
    amount -= amount
elif num > 0:
    hb = round(random.uniform(0.01,amount)/num,2)
    hb_dict[hb] = xingming
    # 算法: 在0.01到红包总金额之间随机一个浮点数 / 红包剩余个数
    print('%s抢到红包%.2f元 剩余%d个!' % (xingming,hb,num))
    amount = round((amount - hb),2)

sleep(1)

转置字典中的 key / value

hb_dict2 = {value:key for key,value in hb_dict.items()}

max_hb = max(hb_dict.items())
print('%s运气最佳 抢得%.2f元!!' % (max_hb[1],max_hb[0]))

随机生成200个***

import random
import string

for num in range(200):
numlist = []
for i in range(12):
numlist.append(random.choice(string.ascii_uppercase+string.digits))

print(''.join(numlist))

with open('200.txt', 'a') as f:     # 'a' 表示追加写入
    f.write(''.join(numlist)+'\n')

f.close

import Image, ImageFont, ImageDraw
text = "EwWIieAT"
im = Image.new("RGB",(130,35), (255, 255, 255))
dr = ImageDraw.Draw(im)

font = ImageFont.truetype("kk.TTF", 24)
#simsunb.ttf 这个从windows fonts copy一个过来
dr.text((10, 5), text, font=font, fill="#000000")

im.show()
im.save("t.png")

缩略图

from PIL import Image
img = Image.open('god.jpg')
img = img.resize((250, 156), Image.ANTIALIAS)
img.save('sharejs_small.jpg')

PythonWare公司提供了免费的图像处理工具包PIL(Python Image Library),该软件包提供了基本的图像处理功能,本文介绍了使用PIL工具包中的Image模块进行比对的过程。

#!/usr/bin/env python

-- coding:utf-8 --

import Image, ImageChops

img1 = Image.open(r'C:\cygwin\tmp\Sonic1.jpg') Capture1.PNG
img2 = Image.open(r'C:\cygwin\tmp\Sonic2.jpg') Diff.jpg
img3 = ImageChops.invert(img2)
Image.blend(img1,img3,0.5).show()

PIL处理图片之加水印

#!/usr/bin/env python

-- coding: utf-8 --

import Image, ImageEnhance, ImageDraw, ImageFont

def text2img(text, font_color="Blue", font_size=25):

"""生成内容为 TEXT 的水印"""

font = ImageFont.truetype('simsun.ttc', font_size)

#多行文字处理
text = text.split('\n')
mark_width = 0
for  i in range(len(text)):
    (width, height) = font.getsize(text[i])
    if mark_width < width:
        mark_width = width
mark_height = height * len(text)

#生成水印图片
mark = Image.new('RGBA', (mark_width,mark_height))
draw = ImageDraw.ImageDraw(mark, "RGBA")
draw.setfont(font)


for i in range(len(text)):
(width, height) = font.getsize(text[i])
draw.text((0, i*height), text[i], fill=font_color)
return mark


​def set_opacity(im, opacity):

"""设置透明度"""

assert opacity >=0 and opacity < 1
if im.mode != "RGBA":
    im = im.convert('RGBA')
else:
    im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im


​def watermark(im, mark, position, opacity=1):

"""添加水印"""

try:
    if opacity < 1:
        mark = set_opacity(mark, opacity)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]:
        print "The mark image size is larger size than original image file."
        return False

    #设置水印位置

    if position == 'left_top':
        x = 0
        y = 0
    elif position == 'left_bottom':
        x = 0
        y = im.size[1] - mark.size[1]
    elif position == 'right_top':
        x = im.size[0] - mark.size[0]
        y = 0
    elif position == 'right_bottom':
        x = im.size[0] - mark.size[0]
        y = im.size[1] - mark.size[1]
    else:
        x = (im.size[0] - mark.size[0]) / 2
        y = (im.size[1] - mark.size[1]) / 2

    layer =Image.new('RGBA', im.size,)
    layer.paste(mark,(x,y))
    returnImage.composite(layer, im, layer)

 exceptExceptionas 
             e:print">>>>>>>>>>> WaterMark EXCEPTION:  "+ str(e)

returnFalsedef 
main():
text = u'Linsir.水印.\[email protected]'# 
text = open('README.md').read().decode('utf-8')# 
print text
im =Image.open('origal.png')
mark = text2img(text)
image = watermark(im, mark,'center',0.9)
if image:
image.save('watermark.png')
image.show()else:print"Sorry, Failed."

if name =='main':

import sys, Image

img = Image.open(sys.argv[1]).convert('YCbCr')

w, h = img.size

data = img.getdata()

cnt = 0

for i, ycbcr in enumerate(data):

y, cb, cr = ycbcr  

if 86 <= cb <= 117 and 140 <= cr <= 168:  

    cnt += 1  

print '%s %s a porn image.'%(sys.argv[1], 'is' if cnt > w 0.3 else 'is not')

运行:
E:/>c:/python25/python test_skin.py 114.jpeg

114.jpeg is a porn image.

import pymysql

获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库

db=pymysql.connect(host="127.0.0.1",user="root",passwd="123456",db="mysql",charset='utf8' )

使用 cursor()方法创建一个游标对象 cursor

cursor = db.cursor()

使用 execute()方法执行 SQL 查询

cursor.execute("SELECT user,host,password from user")

使用 fetchall()方法获取所有行.

data = cursor.fetchall()

print(data)
cursor.close()#关闭游标
db.close()#关闭数据库连接

import pymysql

db = pymysql.connect(host='10.3.1.174',user='root',password='123456',db='test')
cursor = db.cursor()

SQL 插入数据

sql = "INSERT INTO employee (first_name, last_name, age, sex, income) " \
"VALUES ('w', 'Eason', '29', 'M', '8000')"

SQL 更新数据

sql = "UPDATE employee first_name = Wang WHERE first_name = w"

SQL 删除数据

sql = "DELETE FROM employee WHERE age > 20"

try:
cursor.execute(sql)
db.commit()
except:
db.rollback()

db.close()










本文转自 chengxuyonghu 51CTO博客,原文链接:http://blog.51cto.com/6226001001/2067258,如需转载请自行联系原作者