`
hereson
  • 浏览: 1427791 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

使用 cStringIO.StringIO 代替临时文件

 
阅读更多
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
-#import os
-#import sys
- #将 lib 目录添加到系统路径,以便导入 lib 目录下的模块
-#app_root = os.path.dirname(__file__)
-#sys.path.insert(0, os.path.join(app_root, 'lib'))
-
-#if sys.getdefaultencoding() != 'utf-8':
-    #reload(sys)
-    #sys.setdefaultencoding('utf-8')
-
-import tempfile
-import StringIO
+import cStringIO
 import urllib
 import web
 import qrcode
 @@ -42,7 +31,6 @@ def GET(self):
         return render.index()
 
 
-# TODO 返回具体错误信息
 class QR(object):
     """处理传来的数据并显示 QR Code 二维码图片
     """
 @@ -51,7 +39,7 @@ def handle_parameter(self, chl, chld, chs):
         """
         if len(chl) > 2953:  # 最大容量
             raise web.badrequest()
-        chld = chld.upper()  # 转换为大写字母
+        chld = chld.upper()
         # chld 是非必需参数,有默认值
         if not chld:
             chld = 'M|4'
 @@ -71,7 +59,7 @@ def handle_parameter(self, chl, chld, chs):
             border = 4
 
         try:
-            chs = chs.lower()  # 转换为小写字母
+            chs = chs.lower()
             size = tuple([int(i) for i in chs.split('x')])
         except:
             raise web.badrequest()
 @@ -139,9 +127,6 @@ def handle_parameter(self, chl, chld, chs):
                 raise web.badrequest()
             error_correction = qrcode.constants.ERROR_CORRECT_H
 
-        # print len(chl)
-        # print version
-        # print size, border
         # 根据 python-qrcode 源码、square_size 及 version 参数求 box_size
         box_size = square_size / ((version * 4 + 17) + border * 2)
         # print box_size
 @@ -181,30 +166,27 @@ def show_image(self, **args):
                 raise web.internalerror()
 
         # im.show()
-        # 将生成的二维码图片保存到临时文件中,用于下面的缩放处理
-        tempfile.tempdir = 'temp'
-        temp_img = tempfile.TemporaryFile()
+        # 将生成的二维码图片保存到内存中,用于下面的缩放处理
+        temp_img = cStringIO.StringIO()
         im.save(temp_img, 'png')
-        temp_img.seek(0)
-        img_data = temp_img.read()  # 获取图片内容
-        im = Image.open(StringIO.StringIO(img_data))
-        x, y = im.size
-        rx, ry = size
-        # TODO 缩放太小不能识别则显示空白,判断图片清晰度
+        img_data = temp_img.getvalue()  # 获取图片内容
+        im = Image.open(cStringIO.StringIO(img_data))
+        x, y = im.size  # 生成的二维码图片大小
+        rx, ry = size  # 用户请求的图片大小
+
         new_im = Image.new("1", (rx, ry), "white")
-        # 将二维码图片粘贴到空白图片中,保持二维码图片居中
+        # 将二维码图片粘贴到空白图片中并保持二维码图片居中
         paste_size = ((rx - x) / 2, (ry - y) / 2, (rx - x) / 2 + x,
                       (ry - y) / 2 + y)  # 粘贴位置
-        new_im.paste(im, paste_size)
-        temp_img.close()  # 删除临时文件
+        new_im.paste(im, paste_size)  # 若位置全为负值则缩放并填充整个目标图片
 
-        temp_img = tempfile.TemporaryFile()
+        temp_img.write('')
         new_im.save(temp_img, 'png')  # 保存粘贴好的图片
-        temp_img.seek(0)
-        new_im_data = temp_img.read()
+        new_im_data = temp_img.getvalue()
         # 图片 MIME 类型
         MIME = ImageMIME().get_image_type(new_im_data)
-        temp_img.close()
+
+        temp_img.close()  # 释放内存
         return (MIME, new_im_data)
 
     def GET(self):

 

分享到:
评论

相关推荐

    python使用cStringIO实现临时内存文件访问的方法

    f = cStringIO.StringIO(res.read()) f 是一个文件对象, 它和:f = open(‘c:/1.jpg’,’rw’) 打开的文件一样 可以向操作本地文件一样对内存文件进行读写 希望本文所述对大家的Python程序设计有所帮助。

    python从网络读取图片并直接进行处理的方法

    本文实例讲述了python从网络读取图片并直接进行处理的方法。分享给大家供大家参考。具体实现方法如下: ... file = cStringIO.StringIO(urllib2.urlopen(url).read()) img = Image.open(file) im

    Python中暂存上传图片的方法

     buf = cStringIO.StringIO()  image.save(buf, image.format,quality=75)  data = buf.getvalue()  a = u.writeFile(‘/this/logo.jpg’,data,True) 应用在 使用django,用户上传图片后,将图片转存到...

    Python StringIO模块实现在内存缓冲区中读写数据

    s = StringIO.StringIO(“JGood is a handsome boy”) s.write(“JGood is a handsome boy \r\n”) s.write(‘okkkk中国’) s.seek(0) print s.read()   #最后4个字节 s.seek(-4, 2) print s.read()   #—-

    艾伯特《Python标准库》中文版

    5. 文件格式 o 5.1. 概览 o 5.2. xmllib 模块 o 5.3. xml.parsers.expat 模块 o 5.4. sgmllib 模块 www.aibbt.com 让未来触手可及o 5.5. htmllib 模块 o 5.6. htmlentitydefs 模块 o 5.7. formatter 模块 o 5.8. ...

    python模块详解

    2.5. StringIO 模块 2.6. cStringIO 模块 2.7. mmap 模块 2.8. UserDict 模块 2.9. UserList 模块 2.10. UserString 模块 2.11. traceback 模块 2.12. errno 模块 2.13. getopt 模块 2.14. getpass 模块 ...

    Python实现批量读取图片并存入mongodb数据库的方法示例

    本文实例讲述了Python实现批量读取图片并存入mongodb数据库的方法...from cStringIO import StringIO from pymongo import MongoClient import gridfs import os import matplotlib.pyplot as plt import matplotlib.im

    详解Python中heapq模块的用法

    heapq 模块提供了堆算法。heapq是一种子节点和父节点排序的树形数据结构。...from cStringIO import StringIO def show_tree(tree, total_width=36, fill=' '): output = StringIO() last_row = -1 for i, n

    使用python 将图片复制到系统剪贴中

    from cStringIO import StringIO ''' 往剪贴板中放入图片 ''' def setImage(data): clip.OpenClipboard() #打开剪贴板 clip.EmptyClipboard() #先清空剪贴板 clip.SetClipboardData(win32con.CF_DIB, data) #将...

    python图片验证码生成代码

    本文实例为大家分享了python图片验证码实现代码,供大家参考,具体内容如下 ... import cStringIO as StringIO except ImportError: import StringIO _letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母 _upper_cas

    使用python读取csv文件快速插入数据库的实例

    import cStringIO import warnings from sqlalchemy import create_engine import sys reload(sys) sys.setdefaultencoding('utf8') warnings.filterwarnings('ignore') engine = create_engine( 'postgresql+...

    fuzzyset:python字符串的简单模糊匹配集

    只需将一个字符串添加到集合中,然后使用.get或[]要求它: >>> a = fuzzyset.FuzzySet() >>> a.add("michael axiak") >>> a.get("micael asiak") [(0.8461538461538461, u'michael axiak')] 结果将是(score, ...

    Python实现将SQLite中的数据直接输出为CVS的方法示例

    本文实例讲述了Python实现将SQLite中的数据直接输出为CVS的方法。分享给大家供大家参考,具体如下: 对于SQLite来说,目前查看还是...import csv, codecs, cStringIO class UnicodeWriter: """ A CSV writer which

    Python实现淘宝秒杀聚划算抢购自动提醒

    本实例能够监控聚划算的抢购按钮,在聚划算整点聚的时间到达时发出提醒(音频文件自己定义位置)并自动弹开页面(URL自己定义)。 同时还可以通过命令行参数自定义刷新间隔时间(默认0.1s)和监控持续时间(默认...

    python实现rest请求api示例

    该代码参考新浪python api,适用于各个开源api请求 ...try: from cStringIO import StringIOexcept ImportError: from StringIO import StringIO try: import jsonexcept ImportError: import simplejson

    Python实现获取本地及远程图片大小的方法示例

    主要介绍了Python实现获取本地及远程图片大小的方法,结合实例形式分析了Python使用PIL、urllib2及cStringIO模块获取本机或远程图片大小信息的相关操作技巧,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics