Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Last active April 18, 2020 18:09
Show Gist options
  • Save jcheng5/2fa1452f708ae23037fa8af8bdaec050 to your computer and use it in GitHub Desktop.
Save jcheng5/2fa1452f708ae23037fa8af8bdaec050 to your computer and use it in GitHub Desktop.
Determine file image size in R
jpeg_dimensions <- function(filename, bytes = 1024) {
bytes <- readBin(filename, "raw", n = bytes)
if (length(bytes) < 2 || bytes[[1]] != 0xFF || bytes[[2]] != 0xD8) {
stop("Couldn't decode jpeg")
}
ff <- which(bytes == 0xFF)
c0 <- which(bytes == 0xC0)
sof0 <- head(ff[ff %in% (c0 - 1)], 1)
if (length(sof0) == 0) {
stop("Couldn't decode jpeg")
}
if (length(bytes) < sof0 + 9) {
stop("Couldn't decode jpeg")
}
height_bytes <- bytes[(sof0 + 5):(sof0 + 6)]
width_bytes <- bytes[(sof0 + 7):(sof0 + 8)]
list(
width = readBin(width_bytes, "integer", 1, 2, endian = "big"),
height = readBin(height_bytes, "integer", 1, 2, endian = "big")
)
}
png_dimensions <- function(filename) {
bytes <- readBin(filename, "raw", n = 24)
if (length(bytes) < 24) {
stop("Couldn't decode png")
}
png_signature <- as.raw(c(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A))
if (!identical(bytes[1:8], png_signature)) {
stop("Couldn't decode png")
}
if (!identical(bytes[13:16], charToRaw("IHDR"))) {
stop("Couldn't decode png")
}
width_bytes <- bytes[17:20]
height_bytes <- bytes[21:24]
list(
width = readBin(width_bytes, "integer", 1, 4, endian = "big"),
height = readBin(height_bytes, "integer", 1, 4, endian = "big")
)
}
gif_dimensions <- function(filename) {
bytes <- readBin(filename, "raw", n = 10)
if (length(bytes) < 10) {
stop("Couldn't decode gif")
}
if (!identical(bytes[1:6], charToRaw("GIF89a")) && !identical(bytes[1:6], charToRaw("GIF87a"))) {
stop("Couldn't decode gif")
}
width_bytes <- bytes[7:8]
height_bytes <- bytes[9:10]
list(
width = readBin(width_bytes, "integer", 1, 2, endian = "little"),
height = readBin(height_bytes, "integer", 1, 2, endian = "little")
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment