python可以将图像文件读取为二进制文件

时间:2011-10-17 14:08:32

标签: python image binary

我需要上传一个图片文件,并按照人们的建议使用MultipartPostHandler.py。 但仍然无法正常工作。 这是我的代码:

params = {"upload", open("12345.jpg", "rb")} // in 'rb'
opener = urllib2.build_opener(MultipartPostHandler)
res = opener.open(url, params)

这是MultipartPostHander中的代码:

def multipart_encode(vars, files, boundary = None, buffer = None):
    if boundary is None:
        boundary = mimetools.choose_boundary()
    if buffer is None:
        buffer = ''
    for(key, value) in vars:
        buffer += '--%s\r\n' % boundary
        buffer += 'Content-Disposition: form-data; name="%s"' % key
        buffer += '\r\n\r\n' + value + '\r\n'
    for(key, fd) in files:
        file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
        filename = fd.name.split('/')[-1]
        contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        buffer += '--%s\r\n' % boundary
        buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
        buffer += 'Content-Type: %s\r\n' % contenttype
        # buffer += 'Content-Length: %s\r\n' % file_size
        fd.seek(0)
        buffer += '\r\n' + fd.read() + '\r\n'
    buffer += '--%s--\r\n\r\n' % boundary
    return boundary, buffer
multipart_encode = Callable(multipart_encode)

https_request = http_request

错误出现在:

buffer += '\r\n' + fd.read() + '\r\n'

错误是:

'ascii' codec can't decode byte 0xff in position 2: ordinal not in range(128)
这个问题让我大吃一惊,请帮帮我吧! THX。

2 个答案:

答案 0 :(得分:1)

我使用Doug Hellman的博客中的MultiPartForm类将文件成功上传到我们的邮件服务器:http://pymotw.com/2/urllib2/index.html#module-urllib2

希望你也可以使用它。

答案 1 :(得分:0)

i think this can save me. aha.

# convert every byte of data to the corresponding 2-digit hexadecimal

enter code here hex_str = str(binascii.hexlify(data))`

# now create a list of 2-digit hexadecimals

hex_list = []

bin_list = []

for ix in range(2, len(hex_str)-1, 2):

    hex = hex_str[ix]+hex_str[ix+1]

    hex_list.append(hex)

    bin_list.append(bin(int(hex, 16))[2:])

#print(bin_list)

bin_str = "".join(bin_list)

print(bin_str)