• Index

保存图片

Reads: 915 Edit

创建模型

class HouseImageData(Base):
    # 表的名字:
    __tablename__ = 'houseimage2'
    # 表的结构:
    id = Column(INTEGER, primary_key=True, nullable=False, autoincrement=True)
    filename = Column(String(100))
    image = Column(LargeBinary(length=65536))
    file_type = Column(String(50))
    house_id_id = Column(INTEGER)

保存图片

def save_house_image_data_to_db(data):
    """
    将数据存入数据库
    :param data:
    :return:
    """
    # 插入数据
    # 创建session对象:
    session = DBSession()
    house_image_data = HouseImageData(
        filename=data.get('filename', ''),
        image=data.get('image', ''),
        file_type=data.get('file_type', ''),
        house_id_id=data.get('house_id_id', 0)
    )

    # 添加到session:
    session.add(house_image_data)
    session.flush()
    id = house_image_data.id
    # 提交即保存到数据库:
    session.commit()
    # 关闭session:
    session.close()

    return id

查询图片

def query_house_data(id):
    # 创建session对象:
    session = DBSession()
    house_image_list = session.query(HouseImageData).filter(HouseImageData.id == id).first()
    # 关闭Session:
    session.close()
    return house_image_list

保存图片

    def test_save_house_image_data_to_db(self):
        logger.info("* ready for test_save_house_image_data_to_db")
        house = dict()
        house['filename'] = 'zillowhouse1.jpg'
        house['house_id_id'] = 10
        house['file_type'] = 'jpg'
        base64_data = None
        with open(file=f'D:\html\zillowhouse1.jpg', mode='rb', ) as f:
            # data = f.read()
            base64_data = base64.b64encode(f.read())
        house['image'] = base64_data

        logger.info(house)
        db.save_house_image_data_to_db(house)

显示图片

以压缩图片的形式展示在网页

    def test_query_house_data(self):
        logger.info("* ready for test_query_house_data")
        id = 2
        house_image = db.query_house_data(id=id)
        image = house_image.image
        print(type(image))

        # 把二进制转成页面显示的base64格式的数据
        img_str = str(image, 'utf-8')

        fo = open("d:/html/show_img1.html", "w")
        fo.write(f"<image src='data:image/jpeg;base64,{img_str}'/>")
        fo.close()

Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。
  • Index
aaaaa