pixeltrix
pixeltrix copied to clipboard
Possible `as_pixeltrix()` enhancements
as_pixeltrix()becomes an S3 genericas_pixeltrix.matrix()adds an optionalcoloursargument.- Some more possible methods that wouldn't require adding anything to
Suggests(you already use the core{grDevices}elsewhere):
# as returned by `png::readPNG()` and friends
as_pixeltrix.array <- function(x, ...) {
as_pixeltrix.raster(grDevices::as.raster(x))
}
# {bittermelon} bitmap object
as_pixeltrix.bm_bitmap <- function(x, colours = NULL, ...) {
m <- as.matrix(x, first_row_is_top = TRUE)
as_pixeltrix.matrix(m, colours = colours)
}
# {bittermelon} pixmap object
as_pixeltrix.bm_pixmap <- function(x, ...) {
as_pixeltrix.raster(grDevices::as.raster(x))
}
# `{magick}` image object
`as_pixeltrix.magick-image` <- function(x, ...) {
as_pixeltrix.raster(grDevices::as.raster(x))
}
as_pixeltrix.raster <- function(x, ...) {
f <- as.factor(as.matrix(x))
m <- matrix(as.integer(f) - 1L, nrow = nrow(x), ncol = ncol(x))
as_pixeltrix.matrix(m, colours = levels(f))
}
# An `as_pixeltrix.nativeRaster()` method would probably need adding
# {farver} and/or {nara} to `Suggests`...
Another possibly useful S3 method:
as.raster.pixeltrix <- function(x, ..., colours = attr(x, "colours")) {
if (nrow(x) > 0L && ncol(x) > 0L) {
cols <- as.character(colours)[as.integer(x) + 1L]
m <- matrix(cols, nrow = nrow(x), ncol = ncol(x))
as.raster(m)
} else {
as.raster(matrix(character(0L), nrow = nrow(x), ncol = ncol(x)))
}
}
In particular this should let {magick} auto-import {pixeltrix} sprites using magick::image_read() and you can use grid::grid.raster(x, interpolate = FALSE) and rasterGrob(x, interpolate = FALSE) as an alternative for graphics...