UnicodeDecodeError:“ascii”编解码器无法解码位置0中的字节0xff:序号不在范围内(128)

2024-09-30 06:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,它使用tinypng api递归地转换图像,由于某些原因它无法工作,我得到:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

我做错什么了?在

import os
import base64
from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode

compress_png = True 
compress_jpg = True
import_dir = '666\product'
output_dir = '666\product'
tiny_png_key = 'xxxxxx'
tiny_png_url = 'https://api.tinypng.com/shrink'

img_count = 0
file_count = 0
compress_count = 0
existing_count = 0


def compressImage(filepath, filedest, overwrite = True):
    global compress_count
    global existing_count
    if not os.path.isfile(filedest) or overwrite: 
        status = ''
        request = Request(tiny_png_url, open(filepath, "rb").read())
        auth = b64encode(bytes("api:" + tiny_png_key)).decode("ascii")
        request.add_header("Authorization", "Basic %s" % auth)
        response = urlopen(request)

        if response.getcode() == 201:
            status = "success";
            headers = response.info()
            result = urlopen(headers["Location"]).read()

            if not os.path.exists(os.path.dirname(filedest)):
                os.makedirs(os.path.dirname(filedest))
            open(filedest, "wb").write(result)
            compress_count += 1
        else:
            status = "failed"
        print 'Compressing: %s\nFile: %s\nStatus: %s\n'%(filepath, img_count, status)
    else:
        existing_count += 1


# loop througs files in import_dir recursively 
for subdir, dirs, files in os.walk(import_dir):
    for file in files:
        filepath = os.path.join(subdir, file)
        fileName, fileExtension = os.path.splitext(file)
        file_count += 1
        if(fileExtension == '.png' and compress_png) or (fileExtension == '.jpg' and compress_jpg):
            img_count += 1
            filedest = filepath.replace(import_dir, output_dir)
            compressImage(filepath, filedest)


print '================'
print 'Total Files: %s'%(file_count)
print 'Total Images: %s'%(img_count)
print 'Images Compressed: %s'%(compress_count)
print 'Images Previously Compressed (Exist in output directory): %s'%(existing_count)

完全错误:

^{pr2}$

Tags: pathinimportimgpngoscountdir
2条回答

你必须对数据进行编码,而不是用户名 我会尝试类似的方法:

def compressImage(filepath, filedest, overwrite = True):
    global compress_count
    global existing_count
    if not os.path.isfile(filedest) or overwrite: 
        status = ''
        data = open(filepath, "rb").read()
        data = base64.b64encode(data)
        request = Request(tiny_png_url, data)
        request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
        auth = "api:" + tiny_png_key
        request.add_header("Authorization", "Basic %s" % auth)
        response = urlopen(request)

使用网站上的示例并按照您所做的方式将其调整为Python 2,似乎对我很有用:

from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode

key = "xxxx_xxxx"
input = "NLMK.png"
output = "tiny-output.png"

request = Request("https://api.tinypng.com/shrink", open(input, "rb").read())

auth = b64encode("api:" + key).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)

response = urlopen(request)
if response.getcode() == 201:
    # Compression was successful, retrieve output from Location header.
    headers = response.info()
    result = urlopen(headers["Location"]).read()
    open(output, "wb").write(result)
else:
    # Something went wrong! You can parse the JSON body for details.
    print("Compression failed")

相关问题 更多 >

    热门问题