R/png_write.R

Defines functions write_png png_filter png_chunk be32

# ============================ #
# PNG writing                  #
# ============================ #

# The payload is written with the encoder settings held fixed, so that a payload
# built here is the same file whatever writes it. Three choices decide the
# bytes. The filter is chosen row by row as the one whose output has the
# smallest sum of absolute values, read as signed bytes, which is the standard
# heuristic; ties go to whichever filter comes first in the order none, up, sub,
# average, paeth. The deflate parameters are fixed in deflate.cpp. The
# compressed stream is cut into chunks of 65536 bytes.

PNG_SIGNATURE <- as.raw(c(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
IDAT_CHUNK <- 65536L
FILTER_ORDER <- c(1L, 3L, 2L, 4L, 5L)   # none, up, sub, average, paeth

#' @noRd
be32 <- function(n) {
    n <- as.numeric(n)
    as.raw(c(n %/% 16777216, (n %/% 65536) %% 256, (n %/% 256) %% 256, n %% 256))
}

#' @noRd
png_chunk <- function(type, payload) {
    body <- c(charToRaw(type), payload)
    crc <- strtoi(substring(digest::digest(body, algo = "crc32", serialize = FALSE),
                            c(1, 3, 5, 7), c(2, 4, 6, 8)), 16L)
    c(be32(length(payload)), body, as.raw(crc))
}

# `m` holds one scanline per row with values 0 to 255, and `bpp` is the number
# of bytes a pixel occupies, which is how far the Sub and Paeth filters look
# back.
#' @noRd
png_filter <- function(m, bpp) {
    h <- nrow(m); w <- ncol(m)
    prev <- integer(w)
    out <- raw(h * (w + 1L))
    shift <- function(v, k) c(integer(k), v[seq_len(w - k)])
    for (r in seq_len(h)) {
        x <- m[r, ]
        a <- shift(x, bpp)
        b <- prev
        cc <- shift(prev, bpp)
        p <- a + b - cc
        pa <- abs(p - a); pb <- abs(p - b); pc <- abs(p - cc)
        paeth <- ifelse(pa <= pb & pa <= pc, a, ifelse(pb <= pc, b, cc))
        cand <- rbind(x, x - a, x - b, x - (a + b) %/% 2L, x - paeth) %% 256L
        cost <- rowSums(abs(ifelse(cand > 127L, cand - 256L, cand)))
        k <- FILTER_ORDER[which.min(cost[FILTER_ORDER])]
        o <- (r - 1L) * (w + 1L)
        out[o + 1L] <- as.raw(k - 1L)
        out[o + 1L + seq_len(w)] <- as.raw(cand[k, ])
        prev <- x
    }
    out
}

# `data` is an integer matrix for grey, colour type 0, or an array of
# height by width by 3 for truecolour, colour type 2.
#' @noRd
write_png <- function(data, path) {
    if (length(dim(data)) == 3L) {
        h <- dim(data)[1]; w <- dim(data)[2]; ctype <- 2L; bpp <- 3L
        m <- matrix(0L, h, w * 3L)
        for (ch in 1:3) m[, seq(ch, w * 3L, by = 3L)] <- data[, , ch]
    } else {
        h <- nrow(data); w <- ncol(data); ctype <- 0L; bpp <- 1L
        m <- data
    }
    storage.mode(m) <- "integer"
    ihdr <- c(be32(w), be32(h), as.raw(c(8L, ctype, 0L, 0L, 0L)))
    z <- deflate_zlib(png_filter(m, bpp))
    idat <- raw(0)
    for (s in seq(1L, length(z), by = IDAT_CHUNK))
        idat <- c(idat, png_chunk("IDAT", z[s:min(s + IDAT_CHUNK - 1L, length(z))]))
    con <- file(path, "wb")
    on.exit(close(con))
    writeBin(c(PNG_SIGNATURE, png_chunk("IHDR", ihdr), idat, png_chunk("IEND", raw(0))),
             con)
    invisible(path)
}

Try the volumr package in your browser

Any scripts or data that you put into this service are public.

volumr documentation built on Dec. 2, 2026, 5:07 p.m.