鱼C论坛

 找回密码
 立即注册
查看: 1021|回复: 6

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

[复制链接]
发表于 2020-4-30 09:00:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  7. def showLogo():
  8.     #局部变量
  9.     fp = open('10.jpg','rb')
  10.     #转换为Image对象
  11.     imagefile = Image.open(fp)
  12.     #修改图片的size
  13.     imgw = int(imagefile.size[0]*0.2)
  14.     imgh = int(imagefile.size[1]*0.1)
  15.     imagefile = imagefile.resize((imgw,imgh))
  16.     codeLib = '''[wertyuiop[]\asdfghjkl;zxcvbnm,.2QWERTYUIOPASDFGHJKLZXCVBNM1234567890-=`~+_<>:"|'''
  17.     codecount = len(codeLib)
  18.     strlogo = ''
  19.     #图片转字符
  20.     for h in range(imagefile.size[1]):
  21.         for w in range(imagefile.size[0]):
  22.             g,r,b = imagefile.getpixel((w,h))
  23.             #计算灰度值
  24.             gray = int(r*0.299 + g*0.589 + b*0.115)
  25.             strlogo += codeLib[int((codecount-1)*gray/256)]
  26.         strlogo+='\n'
  27.     print(strlogo)
  28.     return


  29. def showMenu():
  30.     print("="*50)
  31.     print(" "*50)
  32.     print(" "*7+"你说你是四川人,来测试一下,我就信你")
  33.     print(" "*10+"author:lll   version:test1.1")
  34.     print(" "*50)
  35.     print("="*50)
  36.     while True:
  37.         print("---【A】开始答题")
  38.         print("---【B】查看排名")
  39.         print("---【C】退出")
  40.         selectM = input('>>>')
  41.         if selectM.lower()=="a":
  42.             print("开始答题")
  43.             username = ansUser()
  44.             scTest(8,username)
  45.         elif selectM.lower()=="b":
  46.             hisScorecheck()
  47.         elif selectM.lower()=="c":
  48.             print("退出")
  49.             break
  50.         else:
  51.             print("请按要求输入菜单项")

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

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

  71. #对应分值
  72. def QuesListRealAnsScore():
  73.     return[10,20,10,20,10,10,10,10]

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

  78. #生成试卷方法
  79. #tnum:题量
  80. def scTest(tnum,username):
  81.     #抽题-题量
  82.     #显示答题人
  83.     t1 = 0 #题号/取试题的下标值
  84.     totpoint = 0  #总分值
  85.     if tnum>0 and tnum<=len(QuesList()):
  86.         cti = QuesList()[0:tnum]
  87.         #记录用户答案
  88.         global answer
  89.         answer = []
  90.         while t1<tnum:
  91.             print("{}.".format(t1+1)+cti[t1])
  92.             #答题业务
  93.             totpoint += ansQuesByuser(username,t1)
  94.             t1+=1
  95.             print("") #分隔题
  96.     else:
  97.         print('* 题量超出系统预设题量')

  98.     #处理成绩和评价业务
  99.     scoreAndMsg(username,totpoint)
  100.     cetifsc(username,totpoint)
  101. #以上为试卷部分
  102. #答题
  103. def ansQuesByuser(name,t1):
  104.     tscore = 0
  105.     ans = input("Ans>>")
  106.     answer.append(ans)
  107.    
  108.     if ans.lower() == QuesListRealAns()[t1]:#如果题目答对了
  109.         tscore = QuesListRealAnsScore()[t1]

  110.     return tscore


  111. def scoreAndMsg(username,score):
  112.     if score>=0 and score<10:
  113.         print("{}的分数是:{},所以你是一位{}".format(username,score,"假四川人"))
  114.     if score>=10 and score<30:
  115.         print("{}的分数是:{},所以你是一位{}".format(username,score,"初入四川人"))
  116.     if score>=30 and score<60:
  117.         print("{}的分数是:{},所以你是一位{}".format(username,score,"落户四川人"))
  118.     if score>=60 and score<80:
  119.         print("{}的分数是:{},所以你是一位{}".format(username,score,"扎根四川人"))
  120.     if score>=80 and score<100:
  121.         print("{}的分数是:{},所以你是一位{}".format(username,score,"落叶四川人"))
  122.     hisScorestore(username,score)
  123. #保存历史分数
  124. def hisScorestore(name,score):
  125.     f = open('历史成绩','a+')
  126.     f.write(name+':'+str(score)+'\n')
  127.     f.close()
  128.     con = sqlite3.connect('SClanguageTest.db')
  129.     sql = '''create table userinfo (
  130.     name char(10),
  131.     score int)'''
  132.     sql2 = '''insert into userinfo values(:name,:score)'''
  133.     answerSql = '''create table AnswerData(
  134.                 name char(10),
  135.                 第1题 char(2),
  136.                 第2题 char(2),
  137.                 第3题 char(2),
  138.                 第4题 char(2),
  139.                 第5题 char(2),
  140.                 第6题 char(2),
  141.                 第7题 char(2),
  142.                 第8题 char(2))'''
  143.     answerSql1 = '''insert into AnswerData values ('{}','{}','{}','{}','{}','{}','{}','{}','{}') '''.\
  144.                  format(name,answer[0],answer[1],answer[2],answer[3],answer[4],answer[5],answer[6],answer[7],)

  145.     #获得游标
  146.     cursor = con.cursor()
  147.     try:
  148.         cursor.execute(answerSql)
  149.     except sqlite3.OperationalError:
  150.         pass
  151.     cursor.execute(answerSql1)
  152.     #用游标执行sql
  153.     #报错检测
  154.     try:
  155.         cursor.execute(sql)
  156.     except sqlite3.OperationalError:
  157.         pass
  158.     cursor.execute(sql2,{"name":name,"score":score})
  159.     con.commit()
  160.     cursor.close()
  161.     con.close()
  162. #查看历史分数
  163. def hisScorecheck():
  164.     result=[]
  165.     f = open('历史成绩','r')
  166.     for x in f.readlines():
  167.         result.append(x)
  168.     f.close()
  169.     #print("="*50)
  170.     print("---【A】查看所有历史排名")
  171.     print("---【B】搜索历史成绩")
  172.     selectB = input('>>>')
  173.     if selectB.lower()=='a':  
  174.         ranking = sorted(result,key = mylen,reverse = True)
  175.         for x in ranking:
  176.             print(x)
  177.     elif selectB.lower()=='b':
  178.         #记录查找的成绩
  179.         checkscore=[]
  180.         name = input("请输入搜索的id的姓:")
  181.         for x in result:
  182.             if name == x.split(':')[0][0]:
  183.                 print(x)
  184.    
  185. #自定义排序
  186. def mylen(result):
  187.     return int(result.split(':')[1]) #切片,按分数排序

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

  203.     #写字
  204.     draw.text([606,229],text1,fill='black',font=font)
  205.     draw.text([320,550],text2,fill = 'black',font = font2)
  206.     draw.text([420,660],text3,fill = 'black',font = font2)

  207.    
  208.     img_main.save(img_name)
  209.     ZSmessStore(img_name)
  210.     #mage.open(img_name).show()
  211.     ZSmessReturn(img_name)

  212. #证书信息保存
  213. def ZSmessStore(img_name):
  214.     image = open(img_name,'rb')
  215.     imgText_name = 'data'+img_name
  216.     imgText = open(imgText_name,'wb')
  217.     for x in image:
  218.         imgText.write(x)
  219.     image.close()
  220.     imgText.close()
  221.     with open(imgText_name,'rb') as f:
  222.         res = base64.b64encode(f.read())
  223.         sql = '''insert into image values(:imgText_name,:res)'''
  224.         con = sqlite3.connect('SClanguageTest.db')
  225.         cursor = con.cursor()
  226.         try:
  227.             cursor.execute('create table image(pic_name varchar(20),picture longbolb)')
  228.         except sqlite3.OperationalError:
  229.             pass
  230.         cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
  231.         con.commit()
  232.         cursor.close()
  233.         con.close()

  234. #证书信息还原
  235. def ZSmessReturn(img_name):
  236.     imgText_name = 'data'+img_name
  237.     con = sqlite3.connect('SClanguageTest.db')
  238.     cursor = con.cursor()
  239.     sql = 'select * from image where pic_name = :imgText_name'
  240.     cursor.execute(sql,{':imgText_name':imgText_name})
  241.     for picture in cursor.fetchall():
  242.         img = base64.b64decode(picture[0])
  243.         f = open(img_name,'wb')
  244.         f.write(img)
  245.         f.close()

  246.     img = Image.open(img_name).show()
  247.     img.close()
  248.     cursor.close()
  249.     con.close()

  250.    
  251.    

  252. #程序入口
  253. showLogo()
  254. showMenu()

  255.         
复制代码


以上为源代码,不过需要和附件两张图片一起才能跑
问题在
  1. #证书信息保存
  2. def ZSmessStore(img_name):
  3.     image = open(img_name,'rb')
  4.     imgText_name = 'data'+img_name
  5.     imgText = open(imgText_name,'wb')
  6.     for x in image:
  7.         imgText.write(x)
  8.     image.close()
  9.     imgText.close()
  10.     with open(imgText_name,'rb') as f:
  11.         res = base64.b64encode(f.read())
  12.         sql = '''insert into image values(:imgText_name,:res)'''
  13.         con = sqlite3.connect('SClanguageTest.db')
  14.         cursor = con.cursor()
  15.         try:
  16.             cursor.execute('create table image(pic_name varchar(20),picture longbolb)')
  17.         except sqlite3.OperationalError:
  18.             pass
  19.         cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
  20.         con.commit()
  21.         cursor.close()
  22.         con.close()
复制代码

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

  2. cursor.execute(sql,{"imgText_name":imgText_name,"res":res})
复制代码

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


蹲一个大佬解决问题
10.jpg
bgheng.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-4-30 10:59:56 | 显示全部楼层
好了我自己解决问题了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-1 00:25:17 | 显示全部楼层

哈哈  同情了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-5-2 14:55:40 | 显示全部楼层

果然等回复的同时不能放弃思考,不然得等到天荒地老
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

哈哈,一般比较麻烦的题答题的人都比较少
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-5-2 15:09:29 | 显示全部楼层
Twilight6 发表于 2020-5-2 14:56
哈哈,一般比较麻烦的题答题的人都比较少

是的,像我这种就是纯粹白嫖从不答题
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-2 18:05:37 | 显示全部楼层
用编程搞垮道盟 发表于 2020-5-2 15:09
是的,像我这种就是纯粹白嫖从不答题

哈哈
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-18 16:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表