Skip to content Skip to sidebar Skip to footer

How Can I Make This Python Script Work With Python 3?

I downloaded this script to help me convert some PNGs. It is however, from 2003 and the first time I tried to run it, it gave me errors for exception syntax. I managed to fix that

Solution 1:

You might want to move the % operator inside the parenthesis.

print (" -  %d PNG files were found at this folder (and subfolders)." % len(pngs))

Solution 2:

In Python 2, plain string literals are bytestrings, while in Python 3 they are Unicode strings. If you want to write a bytestring literal, use the b prefix, e.g. b"\x89PNG\r\n\x1a\n". Python 3 is strict when it comes to mixing bytestrings with Unicode strings.

Other differences are that in Python 3, print is now a normal function, not a statement, the range function returns a generator, like xrange in Python 2, and that input is like raw_input in Python 2 (there's no equivalent of Python 2's input function in Python 3 - it was dropped because it was deemed unsafe).

Here's my attempt to translate the code into Python 3 (incidentally, using from something import * is discouraged because it could inadvertently hide many names; import only those names you wish to use):

from struct import *
from zlib import *
import stat
import sys
import os

defgetNormalizedPNG(filename):
    pngheader = b"\x89PNG\r\n\x1a\n"

    file = open(filename, "rb")
    oldPNG = file.read()
    file.close()

    if oldPNG[:8] != pngheader:
        returnNone

    newPNG = oldPNG[:8]

    chunkPos = len(newPNG)

    # For each chunk in the PNG file    while chunkPos < len(oldPNG):

        # Reading chunk
        chunkLength = oldPNG[chunkPos:chunkPos+4]
        chunkLength = unpack(">L", chunkLength)[0]
        chunkType = oldPNG[chunkPos+4 : chunkPos+8]
        chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength]
        chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12]
        chunkCRC = unpack(">L", chunkCRC)[0]
        chunkPos += chunkLength + 12# Parsing the header chunkif chunkType == b"IHDR":
            width = unpack(">L", chunkData[0:4])[0]
            height = unpack(">L", chunkData[4:8])[0]

        # Parsing the image chunkif chunkType == b"IDAT":
            try:
                # Uncompressing the image chunk
                bufSize = width * height * 4 + height
                chunkData = decompress( chunkData, -8, bufSize)

            except Exception as e:
                # The PNG image is normalizedreturnNone# Swapping red & blue bytes for each pixel
            newdata = b""for y inrange(height):
                i = len(newdata)
                newdata += chunkData[i]
                for x inrange(width):
                    i = len(newdata)
                    newdata += chunkData[i+2]
                    newdata += chunkData[i+1]
                    newdata += chunkData[i+0]
                    newdata += chunkData[i+3]

            # Compressing the image chunk
            chunkData = newdata
            chunkData = compress( chunkData )
            chunkLength = len( chunkData )
            chunkCRC = crc32(chunkType)
            chunkCRC = crc32(chunkData, chunkCRC)
            chunkCRC = (chunkCRC + 0x100000000) % 0x100000000# Removing CgBI chunk        if chunkType != b"CgBI":
            newPNG += pack(">L", chunkLength)
            newPNG += chunkType
            if chunkLength > 0:
                newPNG += chunkData
            newPNG += pack(">L", chunkCRC)

        # Stopping the PNG file parsingif chunkType == b"IEND":
            breakreturn newPNG

defupdatePNG(filename):
    data = getNormalizedPNG(filename)
    if data != None:
        file = open(filename, "wb")
        file.write(data)
        file.close()
        returnTruereturn data

defgetFiles(base):
    global _dirs
    global _pngs
    if base == ".":
        _dirs = []
        _pngs = []

    if base in _dirs:
        return

    files = os.listdir(base)
    for file in files:
        filepath = os.path.join(base, file)
        try:
            st = os.lstat(filepath)
        except os.error:
            continueif stat.S_ISDIR(st.st_mode):
            ifnot filepath in _dirs:
                getFiles(filepath)
                _dirs.append( filepath )

        elif file[-4:].lower() == ".png":
            ifnot filepath in _pngs:
                _pngs.append( filepath )

    if base == ".":
        return _dirs, _pngs

print ("iPhone PNG Images Normalizer v1.0")
print (" ")
print ("[+] Searching PNG files..."),
dirs, pngs = getFiles(".")
print ("ok")

iflen(pngs) == 0:
    print (" ")
    print ("[!] Alert: There are no PNG files found. Move this python file to the folder that contains the PNG files to normalize.")
    exit()

print (" ")
print (" -  %d PNG files were found at this folder (and subfolders)." % len(pngs))
print (" ")
whileTrue:
    normalize = input("[?] Do you want to normalize all images (Y/N)? ").lower()
    iflen(normalize) > 0and (normalize[0] == "y"or normalize[0] == "n"):
        break

normalized = 0if normalize[0] == "y":
    for ipng inrange(len(pngs)):
        perc = (float(ipng) / len(pngs)) * 100.0print ("%.2f%% %s" % (perc, pngs[ipng]))
        if updatePNG(pngs[ipng]):
            normalized += 1print (" ")
print ("[+] %d PNG files were normalized." % normalized)

Solution 3:

What happens when you try % str(len(pngs))?

Post a Comment for "How Can I Make This Python Script Work With Python 3?"