Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EduardoOliveira/d21b40a4443de56f0b1781d872a69aea to your computer and use it in GitHub Desktop.
Save EduardoOliveira/d21b40a4443de56f0b1781d872a69aea to your computer and use it in GitHub Desktop.
func getImageAspectRatio(height, width int) string {
var distance float64
var ratio string
r := float64(width) / float64(height)
distance = math.Abs(r - (16.0 / 9.0))
ratio = "16by9"
if r == 1.0 {
ratio = "1by1"
return ratio
}
if width > height {
if math.Abs(r-(5.0/4.0)) < distance {
distance = math.Abs(r - (5.0 / 4.0))
ratio = "5by4"
}
if math.Abs(r-(4.0/3.0)) < distance {
distance = math.Abs(r - (4.0 / 3.0))
ratio = "4by3"
}
if math.Abs(r-(3.0/2.0)) < distance {
distance = math.Abs(r - (3.0 / 2.0))
ratio = "3by2"
}
if math.Abs(r-(5.0/3.0)) < distance {
distance = math.Abs(r - (5.0 / 3.0))
ratio = "5by3"
}
if math.Abs(r-(3.0/1.0)) < distance {
distance = math.Abs(r - (3.0 / 1.0))
ratio = "3by1"
}
} else {
if math.Abs(r-(4.0/5.0)) < distance {
distance = math.Abs(r - (4.0 / 5.0))
ratio = "4by5"
}
if math.Abs(r-(3.0/4.0)) < distance {
distance = math.Abs(r - (3.0 / 4.0))
ratio = "3by4"
}
if math.Abs(r-(2.0/3.0)) < distance {
distance = math.Abs(r - (2.0 / 3.0))
ratio = "2by3"
}
if math.Abs(r-(3.0/5.0)) < distance {
distance = math.Abs(r - (3.0 / 5.0))
ratio = "3by5"
}
if math.Abs(r-(9.0/16.0)) < distance {
distance = math.Abs(r - (9.0 / 16.0))
ratio = "9by16"
}
if math.Abs(r-(1.0/2.0)) < distance {
distance = math.Abs(r - (1.0 / 2.0))
ratio = "1by2"
}
if math.Abs(r-(1.0/3.0)) < distance {
distance = math.Abs(r - (1.0 / 3.0))
ratio = "1by3"
}
}
return ratio
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment