Skip to content

Instantly share code, notes, and snippets.

@msukmanowsky
Last active May 11, 2018 12:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msukmanowsky/7547012 to your computer and use it in GitHub Desktop.
Save msukmanowsky/7547012 to your computer and use it in GitHub Desktop.
A little Python script and a Java Pig UDF showing how to produce aspect ratios for any arbitrary screen resolution.
def gcf(n, m):
"""Get the greatest common factor between two integers."""
if m < n:
m, n = n, m
while True:
remainder = m % n
if remainder == 0:
return n
else:
m = n
n = remainder
def aspect_ratio(width, height):
"""Return the aspect ratio as a string
>>> aspect_ratio(1920, 1080)
16:9
"""
gcf_ = gcf(width, height)
return '{}:{}'.format(width/gcf_, height/gcf_)
def show_aspect_ratio(width, height):
ar = aspect_ratio(width, height)
print '{}x{} = {}'.format(width, height, ar)
if __name__ == '__main__':
show_aspect_ratio(1920, 1080)
show_aspect_ratio(1280, 800)
show_aspect_ratio(1600, 900)
package com.parsely.pig.screens;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
/**
* This UDF takes a tuple with two positive ints specified 0 -> width
* and 1 -> height and returns the aspect ratio for the resolution.
*
* Aspect ratio is defined as width/GCF:height/GCF where GCF is the
* greatest common factor between width and height.
*
* Example:
* {@code
* DEFINE AspectRatio com.parsely.pig.screens.AspectRatio();
*
* -- input:
* -- (1920,1080)
* input = LOAD 'input' AS (width:int, height:int);
*
* ar = FOREACH input GENERATE width, height, AspectRatio(width, height);
*
* DUMP ar;
* -- (1920,1080,16:9)
* }
*
*/
public class AspectRatio extends EvalFunc<String> {
public AspectRatio() {}
@Override
public String exec(Tuple tuple) throws IOException {
if (tuple.size() != 2) {
throw new IOException("AspectRatio requires a tuple with two ints (width:int, height:int).");
}
int width = (Integer)tuple.get(0);
int height = (Integer)tuple.get(1);
if (width <= 0 || height <= 0) {
// Catch divide by zero error as well as negative
return null;
}
long hcf = highestCommonFactor(width, height);
return "" + width / hcf + ":" + height / hcf;
}
/**
* Find the highest common factor between two longs. Based on a modified version
* of Euclid's algo found on http://stackoverflow.com/questions/17153401/how-calculate-aspect-ratio-from-dimensions-of-image?answertab=votes#tab-top
* @param n
* @param m
* @return highest common factor that evenly divides both n and m
*/
private long highestCommonFactor(long n, long m) {
long temp;
long remainder;
if (m < n) {
temp = m;
m = n;
n = temp;
}
while (true) {
remainder = m % n;
if (remainder == 0)
return n;
else
m = n;
n = remainder;
}
}
}
1920x1080 = 16:9
1280x800 = 8:5
1600x900 = 16:9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment