用编程搞垮道盟 发表于 2020-4-30 09:00:27

我想把图片存进数据库再取出来还原

#考试应用
#从logo - 菜单 - 选项 - 试卷(答题人/试题/答案/分值) - 答题 - 分数/结论 - 证书
from PIL import Image,ImageDraw,ImageFont
import sqlite3
import datetime
import base64

def showLogo():
    #局部变量
    fp = open('10.jpg','rb')
    #转换为Image对象
    imagefile = Image.open(fp)
    #修改图片的size
    imgw = int(imagefile.size*0.2)
    imgh = int(imagefile.size*0.1)
    imagefile = imagefile.resize((imgw,imgh))
    codeLib = '''\asdfghjkl;zxcvbnm,.2QWERTYUIOPASDFGHJKLZXCVBNM1234567890-=`~+_<>:"|'''
    codecount = len(codeLib)
    strlogo = ''
    #图片转字符
    for h in range(imagefile.size):
      for w in range(imagefile.size):
            g,r,b = imagefile.getpixel((w,h))
            #计算灰度值
            gray = int(r*0.299 + g*0.589 + b*0.115)
            strlogo += codeLib
      strlogo+='\n'
    print(strlogo)
    return


def showMenu():
    print("="*50)
    print(" "*50)
    print(" "*7+"你说你是四川人,来测试一下,我就信你")
    print(" "*10+"author:lll   version:test1.1")
    print(" "*50)
    print("="*50)
    while True:
      print("---【A】开始答题")
      print("---【B】查看排名")
      print("---【C】退出")
      selectM = input('>>>')
      if selectM.lower()=="a":
            print("开始答题")
            username = ansUser()
            scTest(8,username)
      elif selectM.lower()=="b":
            hisScorecheck()
      elif selectM.lower()=="c":
            print("退出")
            break
      else:
            print("请按要求输入菜单项")

#以下为试卷部分
def QuesList():
    t1 = '''“包谷”是指()\nA农民B小麦C蝗虫D玉米\n'''
    t2 = '''“批噻噻”是形容一个人()\nA舌头长,搬弄是非B一种腌制品C长得强壮D一种交通工具\n'''
    t3 = '''“叮叮猫”是指()\nA猫猫好可怜B蜻蜓C人长得瘦小D螳螂\n'''
    t4 = '''“泡梢”是()
A骂一个中年妇女体型象泡菜罐B指卖泡菜的少女C夸年轻女孩发育的好,长得水灵D一种泡菜名称\n'''
    t5 = '''“梭椰子”是()
A给买椰子的人取得绰号B骂一妇女体型象椰子C夸小伙子肌肉发达D骂一女人乱搞男女关系\n'''
    t6 = '''“秋瓣儿”是()
A说某人厉害B说某人是黑社会打手C骂某人土气、精神涣散D夸某女孩会持家\n'''
    t7 = '''同音听力“风丝麻木”是形容某人()
A小偷小摸B少男痴情C调皮捣蛋D少女怀春'''
    t8 = '''“豁皮”是()
A说某人是单眼皮B豆腐皮C鸡皮D骂某人是丑八怪'''
    return

#参考答案
def QuesListRealAns():
    return['d','d','d','d','d','c','d','a']

#对应分值
def QuesListRealAnsScore():
    return

#答题人
def ansUser():
    name = input("请输入你的姓名:")
    return name

#生成试卷方法
#tnum:题量
def scTest(tnum,username):
    #抽题-题量
    #显示答题人
    t1 = 0 #题号/取试题的下标值
    totpoint = 0#总分值
    if tnum>0 and tnum<=len(QuesList()):
      cti = QuesList()
      #记录用户答案
      global answer
      answer = []
      while t1<tnum:
            print("{}.".format(t1+1)+cti)
            #答题业务
            totpoint += ansQuesByuser(username,t1)
            t1+=1
            print("") #分隔题
    else:
      print('* 题量超出系统预设题量')

    #处理成绩和评价业务
    scoreAndMsg(username,totpoint)
    cetifsc(username,totpoint)
#以上为试卷部分
#答题
def ansQuesByuser(name,t1):
    tscore = 0
    ans = input("Ans>>")
    answer.append(ans)
   
    if ans.lower() == QuesListRealAns():#如果题目答对了
      tscore = QuesListRealAnsScore()

    return tscore


def scoreAndMsg(username,score):
    if score>=0 and score<10:
      print("{}的分数是:{},所以你是一位{}".format(username,score,"假四川人"))
    if score>=10 and score<30:
      print("{}的分数是:{},所以你是一位{}".format(username,score,"初入四川人"))
    if score>=30 and score<60:
      print("{}的分数是:{},所以你是一位{}".format(username,score,"落户四川人"))
    if score>=60 and score<80:
      print("{}的分数是:{},所以你是一位{}".format(username,score,"扎根四川人"))
    if score>=80 and score<100:
      print("{}的分数是:{},所以你是一位{}".format(username,score,"落叶四川人"))
    hisScorestore(username,score)
#保存历史分数
def hisScorestore(name,score):
    f = open('历史成绩','a+')
    f.write(name+':'+str(score)+'\n')
    f.close()
    con = sqlite3.connect('SClanguageTest.db')
    sql = '''create table userinfo (
    name char(10),
    score int)'''
    sql2 = '''insert into userinfo values(:name,:score)'''
    answerSql = '''create table AnswerData(
                name char(10),
                第1题 char(2),
                第2题 char(2),
                第3题 char(2),
                第4题 char(2),
                第5题 char(2),
                第6题 char(2),
                第7题 char(2),
                第8题 char(2))'''
    answerSql1 = '''insert into AnswerData values ('{}','{}','{}','{}','{}','{}','{}','{}','{}') '''.\
               format(name,answer,answer,answer,answer,answer,answer,answer,answer,)

    #获得游标
    cursor = con.cursor()
    try:
      cursor.execute(answerSql)
    except sqlite3.OperationalError:
      pass
    cursor.execute(answerSql1)
    #用游标执行sql
    #报错检测
    try:
      cursor.execute(sql)
    except sqlite3.OperationalError:
      pass
    cursor.execute(sql2,{"name":name,"score":score})
    con.commit()
    cursor.close()
    con.close()
#查看历史分数
def hisScorecheck():
    result=[]
    f = open('历史成绩','r')
    for x in f.readlines():
      result.append(x)
    f.close()
    #print("="*50)
    print("---【A】查看所有历史排名")
    print("---【B】搜索历史成绩")
    selectB = input('>>>')
    if selectB.lower()=='a':
      ranking = sorted(result,key = mylen,reverse = True)
      for x in ranking:
            print(x)
    elif selectB.lower()=='b':
      #记录查找的成绩
      checkscore=[]
      name = input("请输入搜索的id的姓:")
      for x in result:
            if name == x.split(':'):
                print(x)
   
#自定义排序
def mylen(result):
    return int(result.split(':')) #切片,按分数排序

#生成证书
def cetifsc(name,score):
    #获取当前时间
    time = datetime.datetime.now()
    #格式化当前时间
    timeStr = time.strftime('%Y%m%d')
    img_name = '{}_{}.jpg'.format(name,timeStr)
    #证书内容
    text1 = '四川话八级证书'
    text2 = '{}同志:'.format(name)
    text3 = '你在四川话八级测试中获得的成绩是{}分'.format(score)
    img_main = Image.open('bgheng.png')#打开图片
    draw = ImageDraw.Draw(img_main)#添加画板
    font = ImageFont.truetype('C:\Windows\Fonts\FZYTK.TTF',80)#字体设置
    font2 = ImageFont.truetype('C:\Windows\Fonts\msyh.ttc',50)

    #写字
    draw.text(,text1,fill='black',font=font)
    draw.text(,text2,fill = 'black',font = font2)
    draw.text(,text3,fill = 'black',font = font2)

   
    img_main.save(img_name)
    ZSmessStore(img_name)
    #mage.open(img_name).show()
    ZSmessReturn(img_name)

#证书信息保存
def ZSmessStore(img_name):
    image = open(img_name,'rb')
    imgText_name = 'data'+img_name
    imgText = open(imgText_name,'wb')
    for x in image:
      imgText.write(x)
    image.close()
    imgText.close()
    with open(imgText_name,'rb') as f:
      res = base64.b64encode(f.read())
      sql = '''insert into image values(:imgText_name,:res)'''
      con = sqlite3.connect('SClanguageTest.db')
      cursor = con.cursor()
      try:
            cursor.execute('create table image(pic_name varchar(20),picture longbolb)')
      except sqlite3.OperationalError:
            pass
      cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
      con.commit()
      cursor.close()
      con.close()

#证书信息还原
def ZSmessReturn(img_name):
    imgText_name = 'data'+img_name
    con = sqlite3.connect('SClanguageTest.db')
    cursor = con.cursor()
    sql = 'select * from image where pic_name = :imgText_name'
    cursor.execute(sql,{':imgText_name':imgText_name})
    for picture in cursor.fetchall():
      img = base64.b64decode(picture)
      f = open(img_name,'wb')
      f.write(img)
      f.close()

    img = Image.open(img_name).show()
    img.close()
    cursor.close()
    con.close()

   
   

#程序入口
showLogo()
showMenu()

      


以上为源代码,不过需要和附件两张图片一起才能跑
问题在#证书信息保存
def ZSmessStore(img_name):
    image = open(img_name,'rb')
    imgText_name = 'data'+img_name
    imgText = open(imgText_name,'wb')
    for x in image:
      imgText.write(x)
    image.close()
    imgText.close()
    with open(imgText_name,'rb') as f:
      res = base64.b64encode(f.read())
      sql = '''insert into image values(:imgText_name,:res)'''
      con = sqlite3.connect('SClanguageTest.db')
      cursor = con.cursor()
      try:
            cursor.execute('create table image(pic_name varchar(20),picture longbolb)')
      except sqlite3.OperationalError:
            pass
      cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
      con.commit()
      cursor.close()
      con.close()


sql = '''insert into image values(:imgText_name,:res)'''

cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
这个位置
会报如下错误
cursor.execute(sql,{':imgText_name':imgText_name})
sqlite3.ProgrammingError: You did not supply a value for binding 1.

蹲一个大佬解决问题

用编程搞垮道盟 发表于 2020-4-30 10:59:56

好了我自己解决问题了

Twilight6 发表于 2020-5-1 00:25:17

用编程搞垮道盟 发表于 2020-4-30 10:59
好了我自己解决问题了

哈哈同情了{:10_245:}

用编程搞垮道盟 发表于 2020-5-2 14:55:40

Twilight6 发表于 2020-5-1 00:25
哈哈同情了

果然等回复的同时不能放弃思考,不然得等到天荒地老

Twilight6 发表于 2020-5-2 14:56:26

用编程搞垮道盟 发表于 2020-5-2 14:55
果然等回复的同时不能放弃思考,不然得等到天荒地老

哈哈,一般比较麻烦的题答题的人都比较少

用编程搞垮道盟 发表于 2020-5-2 15:09:29

Twilight6 发表于 2020-5-2 14:56
哈哈,一般比较麻烦的题答题的人都比较少

是的,像我这种就是纯粹白嫖从不答题

Twilight6 发表于 2020-5-2 18:05:37

用编程搞垮道盟 发表于 2020-5-2 15:09
是的,像我这种就是纯粹白嫖从不答题

哈哈
页: [1]
查看完整版本: 我想把图片存进数据库再取出来还原