【问题标题】:python3 converting binary data to string and backpython3将二进制数据转换为字符串并返回
【发布时间】:2019-02-26 13:33:36
【问题描述】:

我正在使用 python3 以二进制模式打开图像 然后在特定标记处拆分该数据 (\xff\xda)

该标记之后的所有内容都存储在一个变量中 我想用 e's 替换所有 a's

但我在将二进制数据转换为字符串时遇到了麻烦:

UnicodeDecodeError : 'ascii' 编解码器无法在位置解码字节 0xe6 13: 序数不在范围内(128)

with open(filein, "rb") as rd:
  with open(fileout,'wb') as wr:
    img = rd.read()
    if img.find(b'\xff\xda'): ## ff da start of scan
        splitimg = img.split(b'\xff\xda', 1)
        wr.write(splitimg[0])
        scanimg = splitimg[1]

        scanglitch = ""
        scanimg = scanimg.encode()

        for letter in scanimg :
            if letter not in 'a': 
                scanglitch += letter
            else :
                scanglitch += 'e'

    print(scanimg)

    wr.write(b'\xff\xda')
    content = scanglitch.decode()
    wr.write(content)

encode() 和 decode() 不正确吗 将二进制数据转换为字符串并返回? 谢谢

【问题讨论】:

  • 请也向我们显示回溯,以便我们知道是哪一行给出了该错误。
  • 您确定首先需要转换为字符串吗? b"this is a byte string".replace(b"a", b"e") 可以将“a”替换为“e”,而无需使用字符串。
  • 抱歉,回溯错误来自带有“scanimg = scanimg.encode()”的行,由于行号不匹配,不确定如何将其添加到我的帖子中

标签: python python-3.x jpeg


【解决方案1】:

在处理二进制数据时,您会希望尽可能保持二进制模式,尤其是因为无法保证您选择的字符串编码无论如何都可以代表所有值。

请记住 bytes 对象基本上是 8 位无符号整数的列表,即使它们具有方便的类似字符串的 b'xyz' 语法。

filein = "download.jpeg"
fileout = "glitch.jpg"

with open(filein, "rb") as rd:
    img = rd.read()
    # We can happily crash here if there's no FFDA; 
    # that means we're not able to process the file anyway
    prelude, marker, scanimg = img.partition(b"\xff\xda")
    scanglitch = []

    for letter in scanimg:  # scanimg is a list of integers, so we have to use `ord()`
        if letter != ord("a"):
            scanglitch.append(letter)
        else:
            scanglitch.append(ord("e"))

with open(fileout, "wb") as wr:
    wr.write(prelude)
    wr.write(marker)
    wr.write(bytes(scanglitch))

(我知道替换逻辑可以写成列表推导式,但我认为这样会更友好。)

【讨论】:

    猜你喜欢
    • 2023-03-02
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多