当我试图在python中从一个url中插入一个图片到excel中时,出现 "胁迫到Unicode:需要字符串或缓冲区,找到cStringIO.StringO "的错误。

问题描述 投票:0回答:1

我试图从一个网址插入一个图像到excel中,但我得到这个错误。

coercing to Unicode: need string or buffer, cStringIO.StringO found

这是我的代码

import cStringIO
from PIL import Image
import urllib

wb = pyExcelerator.Workbook()
ws = wb.add_sheet('sheet 1')
url= 'this url contains the url of an image'

f = urllib.urlopen(url)
buf = f.read()
fileIO = cStringIO.StringIO(buf)
img = Image.open(fileIO).convert("RGB")
img.thumbnail((71, 100), Image.ANTIALIAS)
img_bmp = cStringIO.StringIO()
img.save(img_bmp, 'BMP')
img_bmp.seek(0)
ws.insert_bitmap(img_bmp, 0, 1)
python bitmap python-imaging-library buffer
1个回答
0
投票

我不得不保存图像并转换为bmp。

import cStringIO
from PIL import Image
import urllib

wb = pyExcelerator.Workbook()
ws = wb.add_sheet('sheet 1')
url= 'this url contains the url of an image'
dir= 'It is a directory location'

f = urllib.urlopen(url)
buf = f.read()
fileIO = cStringIO.StringIO(buf)
img = Image.open(fileIO).convert("RGB")
img.thumbnail((71, 100), Image.ANTIALIAS)
img_bmp = cStringIO.StringIO()

#this is the one that converts the image to bmp
img.save(img_bmp, 'BMP') 

with open('{}/prova_img.bmp'.format(dir), 'w') as file_handle:
    file_handle.write(img_bmp.getvalue())

ws.insert_bitmap('{}/the_bitmap_image.bmp'.format(dir), 0, 1)
© www.soinside.com 2019 - 2024. All rights reserved.