首页 文章

对于带有基数2的int(),Python无效的文字

提问于
浏览
0

我正在尝试一个简单的隐写术python程序 . 编码工作,但我得到错误ValueError:int()的无效文字与基2:'0b#99c1f#......值应该是二进制,我找不到错误 . 我正在使用python 2.7,这是代码:

from PIL import Image
import binascii
import optparse


def rgb2hex(r,g,b):
    return '#{:02x}{:02x}{:02x}'.format(r,g,b)


def hex2rgb(hexcode):
    return tuple(map(ord,hexcode[1:].decode('hex')))


def str2bin(message):
    binary = bin(int(binascii.hexlify(message), 16))
    return binary[2:]


def bin2str(binary):
    message = binascii.unhexlify('%x' %(int('0b' + binary, 2)))
    return message


def encode(hexcode, digit):
    if hexcode[-1] in ('0', '1', '2', '3', '4', '5'):
        hexcode = hexcode[:-1]+digit
        return hexcode
    else:
        return None


def decode(hexcode):
    if(hexcode[-1] in ('0','1')):
        return hexcode[:-1]
    else:
        return None


def hide(filename, message):
    img = Image.open(filename)
    binary = str2bin(message) + '1111111111111110'
    if img.mode in ('RGBA'):
        img = img.convert('RGBA')
        datas = img.getdata()

        newData = []
        digit = 0
        temp = ''
        for item in datas:
            if (digit < len(binary)):
                newpix = encode(rgb2hex(item[0], item[1], item[2]), binary[digit])
                if newpix == None:
                    newData.append(item)
                else:
                    r,g,b = hex2rgb(newpix)
                    newData.append((r,g,b,255))
                    digit += 1

            else:
                newData.append(item)

        img.putdata(newData)
        img.save(filename, "bmp")
        return "Completed!"
    return "Incorrect Image mode"


def retr(filename):
    img = Image.open(filename)
    binary = ''

    if img.mode in ('RGBA'):
        img = img.convert('RGBA')
        datas = img.getdata()

        for item in datas:
            digit = decode(rgb2hex(item[0], item[1], item[2]))
            if digit == None:
                pass
            else:
                binary = binary + digit
                if (binary[-16:] == '1111111111111110'):
                    print "Success"
                    return bin2str(binary[:-16])

        return bin2str(binary)

    return "incorrect image mode"


def Main():

    parser = optparse.OptionParser('usage %prog -e/-d <target file>')
    parser.add_option('-e', dest='hide', type='string', help='target picture')
    parser.add_option('-d', dest='retr', type='string', help='target picture')

    (options, args) = parser.parse_args()
    if options.hide != None:
        text = raw_input("Enter a message: ")
        print hide(options.hide, text)

    elif options.retr != None:
        print retr(options.retr)

    else:
        print parser.usage
        exit(0)


Main()

1 回答

  • 1

    此行导致错误:

    binary = binary + digit
    

    在那里, digit 是一个带有十六进制值的字符串(例如 #003f7 ),它与一个应该是二进制字符串的连接(但实际上是类似于: #003f7#003f7... ) . 然后,您将该值传递给 bin2str() .

相关问题