matt-dray / pixeltrix

:space_invader::computer_mouse: R package: make pixel art interactively in a plot window, get a matrix, make a gif
Other
21 stars 0 forks source link

Possible `as_pixeltrix()` enhancements #38

Open trevorld opened 1 month ago

trevorld commented 1 month ago
# 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`...
trevorld commented 1 month ago

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...