【问题标题】:Use python to output image from cx_oracle blob使用 python 从 cx_oracle blob 输出图像
【发布时间】:2012-02-11 02:57:35
【问题描述】:

我已将图像存储在 BLOB 列中的 oracle 表中。我使用 JAVA 读取和输出图像并写入数据。我想用 python 做同样的事情(获取我的图像并分发它)。我正在使用 Flask 框架和 cx_Oracle。

我设法将我的 BLOB 内容放入我的应用程序,但我不确定如何从中生成图像。

我知道在 Java 中我使用过:

OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy( new ByteArrayInputStream(doc.getContent()),out);
out.flush();

其中 doc.getContent() 是我的 BLOB 内容。

【问题讨论】:

    标签: python flask cx-oracle


    【解决方案1】:

    使用 Flask 和你的帮助:

    @app.route('/_photo/')
    def gripur():
    
        conn = cx_Oracle.connect("*****","****",make_dsn_tns(get_config_string()))
        curs = conn.cursor()
        #find photo
        document=curs.execute('select myblob from mytable where id=34234')
        row = cursor.fetchone()
        imageBlob = row[0]
    
        blob= imageBlob.read()
        response = make_response(blob)
        response.headers["Content-type"] = "image/jpeg"
        conn.close()
    
        return response
    

    【讨论】:

      【解决方案2】:

      如果您有数据并且只需要将其写入磁盘上的图像文件,您可以将其直接写入以二进制模式打开的文件中。

      import cx_oracle
      
      sql = 'select img_fld from img_table where id=1234'
      imagePath = './output/image.png'
      
      conn = cx_oracle.connect('your_connection_string')
      
      cursor = conn.cursor()
      cursor.execute(sql)
      
      #assuming one row of image data is returned
      row = cursor.fetchone()
      imageBlob = row[0]
      
      #open a new file in binary mode
      imageFile = open(imagePath,'wb')
      
      #write the data to the file
      imageFile.write(imageBlob.read())
      
      #closing the file flushes it to disk
      imageFile.close()
      
      cursor.close()
      conn.close()
      

      如果您需要一个“类文件”对象而不写入磁盘,您可以使用 cStringIO 模块创建内存缓冲区。 https://docs.python.org/library/stringio.html

      【讨论】:

      • ig 出错 imageFile.write(imageBlob) TypeError: must be string or buffer, not cx_Oracle.LOB
      • @asdfme123 你错过了.read()。请改用imageFile.write(imageBlob.read())
      猜你喜欢
      • 2014-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多