首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >img.show()不显示图像窗口

img.show()不显示图像窗口
EN

Stack Overflow用户
提问于 2022-11-10 16:42:58
回答 1查看 14关注 0票数 0

我对此并不熟悉,但我正在编写一个程序,首先创建和加密密码,然后将加密的密码编码到下载的图像中,最后将编码的图像插入数据库。

这是我的密码

代码语言:javascript
复制
import os
import re
import urllib.request
import mysql.connector
from Password import *
import image
import stepic
from PIL import Image

targetFileDir='MTUFacultyImages'
isExist = os.path.exists(targetFileDir)
if not isExist:  
    # Create a new directory because it does not exist 
    os.makedirs(targetFileDir)

def convertImageToBinaryData(filename):
    # Convert digital data to binary format
    with open(filename, 'rb') as file:
        binaryData = file.read()
    return binaryData

def writeBinaryDataToImage(data, filename):
    # Convert binary data to proper format and write it on Hard Disk
    with open(filename, 'wb') as file:
        file.write(data)
    
# connect the db
db_connection = mysql.connector.connect( 
host= "localhost", 
user= "root", 
password= "password") 
#database="faculty_db" ) 
# creating database
db_cursor = db_connection.cursor()

faculty_list_info=[]

class faculty_record:
    def __init__(self,first_Name, last_Name, title, office, phone, e_mail, photo_file_name, photo_link ):
        self.First_Name=first_Name
        self.Last_Name=last_Name
        self.Title=title
        self.Office=office
        self.Phone=phone
        self.E_mail=e_mail
        self.PhotoFileName=photo_file_name
        self.PhotoLink=photo_link
    

def Faculty_record_extraction():
    req =urllib.request.Request('https://www.mtu.edu/computing/departments/applied-computing/faculty/',headers={'User-Agent': 'Mozilla/5.0'})
    page = urllib.request.urlopen(req)  
    #read the string 
    str=page.read().decode('utf-8')
    print(str)
    #construct pattern to search
    pattern_str=("<img.+src=\"([\S./-]+/([\S.-]+.jpg))\".+/>\s+</a>\s+</div>\s+<div\s+class=\"person_bio\">\s+<div\s+class=\"personal\">\s+"
                 "<h2>\s*<a\s+href=\"[\S\.-/]+\">([\D]+)\s+([\D]+)</a></h2>\s*"
                 "<ul\s+class=\"none\">\s*<li>([A-Za-z,\s]+)</li>\s*<li>.+</li>\s*</ul>\s*</div>\s*"
                      "<div\s+class=\"left\">\s*<div\s+class=\"contact\">\s*<ul\s+class=\"none\">"
                      "\s*<li\s+class=\"email-address\">\s*<a\s+href=\"\S+\">(\S+)</a>\s*</li>\s*<li\s+class=\"phone-number\">\s*<a\s+href=\"\S+\">([\S-]+)</a>\s*</li>\s*"
                      "<li\s+class=\"place\">([\w\s]+)</li>\s*</ul>\s*</div>")

    global faculty_list_info
    faculty_list_search=re.findall(pattern_str,str)
    # download images
    image_url_prefix='https://www.mtu.edu'  
    opener = urllib.request.URLopener()   ## read https://stackoverflow.com/questions/34957748/http-error-403-forbidden-with-urlretrieve
    opener.addheader('User-Agent', 'Mozilla/5.0')
    for each_faculty in faculty_list_search:       
        #print("First Name: ", each_faculty[2],"Last Name",each_faculty[3])
        print(image_url_prefix+each_faculty[0])
        opener.retrieve(image_url_prefix+each_faculty[0],targetFileDir+"/"+each_faculty[1]) # download and save images
        #download_file(image_url_prefix+each_faculty[0],targetFileDir+"/"+each_faculty[1])
        faculty_list_info.append(faculty_record(each_faculty[2],each_faculty[3],each_faculty[4],each_faculty[7],each_faculty[6],each_faculty[5],each_faculty[1],image_url_prefix+each_faculty[0])) # save faculty info

def Faculty_record_Store():
    global db_cursor

    # if faculty_db exists, drop/ remove it
    db_cursor.execute("SHOW DATABASES LIKE 'faculty_db'")
    for db in db_cursor: 
       print(db)
    if db_cursor.rowcount>0:
        print('faculty_db found, I will drop it now')
        db_cursor.execute("DROP DATABASE faculty_db")

    # executing cursor with execute method and pass SQL query
    db_cursor.execute("CREATE DATABASE faculty_db") 

    # get list of all databases 
    db_cursor.execute("SHOW DATABASES") 

    #print all databases 
    for db in db_cursor: 
           print(db)
    db_cursor.execute("USE faculty_db")

    # creating the table 
    db_cursor.execute("CREATE TABLE faculty("
    "first_Name varchar(20), last_Name varchar(20),title varchar(60), office varchar(20),phone varchar(20),e_mail varchar(20),photo_file_name varchar(128),photo_link varchar(512),photo LONGBLOB NOT NULL,"
    "CONSTRAINT PK_FACULTY PRIMARY KEY (first_Name,last_Name))")

    #Get database table 
    db_cursor.execute("SHOW TABLES") 
    for table in db_cursor: 
         print(table)

    # store faculty records to the db
    global faculty_list_info
    add_records = "INSERT INTO faculty(first_Name,last_Name,title,office,phone,e_mail,photo_file_name,photo_link,photo) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
    records_vals= []
    for each_faculty in faculty_list_info:
        each_faculty_photo = convertImageToBinaryData(targetFileDir+"/"+each_faculty.PhotoFileName)
        records_vals.append((each_faculty.First_Name,each_faculty.Last_Name,each_faculty.Title,each_faculty.Office,each_faculty.Phone,each_faculty.E_mail, each_faculty.PhotoFileName, each_faculty.PhotoLink,each_faculty_photo))
    print("********************************************************")   
    print(records_vals)

    #insert records to the database  
    db_cursor.executemany(add_records,records_vals) 
    db_connection.commit() 
    print(db_cursor.rowcount, "Record Inserted")

    # show records
    db_cursor.execute("SELECT * FROM faculty WHERE e_mail='whzhou@mtu.edu'")
    myresult = db_cursor.fetchall()
    for query_record in myresult:
        #print(x)
        writeBinaryDataToImage(query_record[8],query_record[0]+query_record[1]+".jpg")
    
# extract the information from the website
Faculty_record_extraction()
Faculty_record_Store()

#Using createPassword(8) and simple_encryption() to create and encrypt password for each faculty member 
faculty_password = []
for each_faculty in faculty_list_info:
    passwd = createPassword(8)
    print("Password : ", passwd)
    encrypted_text = simple_encryption(passwd,12)
    print("Cipher: ",encrypted_text)    
    faculty_password.append(encrypted_text)

# using information_hiding to encode each photo with hidden password 
def information_hiding(imagefile,text):
    for each_faculty_photo in each_faculty:
        imagefile = each_faculty_photo
        text = faculty_password

    print(information_hiding(each_faculty_photo, faculty_password))

# #to insert the photos with hidden pword into the table faculty
    image_vals =[]
    for x in faculty_password:
        img = Image.open(each_faculty_photo)
        img.show()
        img_encoded = stepic.encode(img, text)
        img_encoded.show()
        img_encoded.save(('hidden' + each_faculty_photo + '.PNG'), 'PNG')
        img_encoded.show()

    add_images = "INSERT INTO faculty (imagefile LONGBLOB NOT NULL) VALUES (%s)"
    for y in img_encoded:
        db_cursor.executemany(add_images,image_vals) 
        db_connection.commit() 
        print(db_cursor.rowcount, "Record Inserted")

我没有收到任何错误,密码已经创建和加密,但图像没有被编码和显示,并无法弄清楚原因。

EN

回答 1

Stack Overflow用户

发布于 2022-11-10 17:45:22

你的问题有一个简单的答案:

图像没有显示的原因是您没有在代码中的任何地方调用information_hinding()函数。

换句话说,如果您提供的代码将被执行,则应该显示映像的函数根本不会运行。这也是为什么您没有得到任何错误,尽管事实上,如果实际运行的函数将失败,引发一个错误。

作为对答案的补充,您提供了更多关于代码的内容:

让我们看一看information_hinding()函数,看看如果调用它,就会得到递归错误,因为它本身内有递归调用,而不需要停止递归:

代码语言:javascript
复制
# using information_hiding to encode each photo with hidden password 
def information_hiding(imagefile,text):
    for each_faculty_photo in each_faculty:
        imagefile = each_faculty_photo
        text = faculty_password
    # >>> RECURSIVE CALL: 
    print(information_hiding(each_faculty_photo, faculty_password))

我还建议您在递归调用之前检查for循环将做什么,因为它的唯一效果是将imagefile设置为each_faculty中的最后一项,并使text存储整个faculty_password列表。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74392497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档