How to change the size of the resolution based on division

Question:

I would like to change the resolution of the image (nHeight = Height of the picture) and make it divisible to 8. I am using the below python code. Can anyone help me for this?

  if (nHeight%8 != 0):
            try:
                while (nHeight%8 == 0):
                    nHeight = nHeight +1
                    print(nHeight%8)
            except:
                pass
Asked By: Cagri

||

Answers:

Do you mean something like this:

while n_height % 8 != 0:
        n_height += 1

If n_height is, let’s say 17, before running the above block, then afterwards it would be 24.

The if block is not necessary, because the while won’t execute if your resolution size is already divisible by 8.

Hope this helps.

Answered By: José Sánchez

Here’s a simpler form that doesn’t use loops or try /except blocks, but math operations:

if nHeight % 8:
    nHeight = nHeight // 8 * 8 + 8
print(nHeight)

The secret is the n // 8 which is called floor division ([Python 2.Docs]: Binary arithmetic operations).
You could also use regular division (on Python 2)… well assuming that nHeight is an integer – which kind of makes sense if the resolution is expressed in pixels.

  • Integer division returns the quotient

  • That is then multiplied by 8 to get the highest 8 multiple, less than our number

  • Finally, added another 8 to get the lowest 8 multiple, greater than our number

The whole expression is equivalent to nHeight = (nHeight // 8 + (1 if nHeight % 8 else 0)) * 8.

Answered By: CristiFati

Your code has a bug: while (nHeight%8 == 0) needs to be while (nHeight%8 != 0). But it doesn’t matter, because what you want to accomplish is easy with a simple expression that eliminates the while loop and if testing altogether:

nHeight = ((nHeight + 7) // 8) * 8

This works for any positive number. // is integer division, throwing away the remainder. By adding 7 before dividing, you don’t change the result if it’s already divisible by 8 but you bump the division result by 1 if it wasn’t; multiplying by 8 again compensates for the division and makes it obvious the result will be divisible by 8.

P.S. it’s quite unusual to see Hungarian notation in Python, it goes against the PEP 8 guidelines.

Answered By: Mark Ransom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.