Convert images to/from nativeRaster

library(grid)
library(nara)

Create a nativeRaster

nr <- nr_new(10, 10, fill = 'white')
class(nr)
#> [1] "nativeRaster"

Save/Load nativeRaster images to/from PNG and JPEG

Both the {png} and {jpeg} packages allow images to be loaded directly as nativeRaster images.

img <- jpeg::readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"), native = TRUE)
class(img)
#> [1] "nativeRaster"
grid.raster(img, interpolate = FALSE)

img <- png::readPNG(system.file("img", "Rlogo.png", package="png"), native = TRUE)
class(img)
#> [1] "nativeRaster"
grid.raster(img, interpolate = FALSE)

# {jpeg} and {png} will automatically detect and save 'nativeRaster' images
jpeg::writeJPEG(img, "test.jpg")
png::writePNG(img, "test.png")

Convert a regular R raster image to/from nativeRaster

ras <- matrix(c('brown', 'darkblue', 'darkblue', 'brown'), 2, 2)
ras
#>      [,1]       [,2]      
#> [1,] "brown"    "darkblue"
#> [2,] "darkblue" "brown"
grid.raster(ras, interpolate = FALSE)

nr <- nara::raster_to_nr(ras)
nr
#>           [,1]      [,2]
#> [1,] -14013787  -7667712
#> [2,]  -7667712 -14013787
#> attr(,"class")
#> [1] "nativeRaster"
grid.raster(nr, interpolate = FALSE)

Convert a regular R array image to/from nativeRaster

arr <- array(c(
  1, 1, 0,
  0, 0, 0,
  0, 0, 0, 
  1, 1, 0
), dim = c(2, 2, 3))

arr
#> , , 1
#> 
#>      [,1] [,2]
#> [1,]    1    0
#> [2,]    1    0
#> 
#> , , 2
#> 
#>      [,1] [,2]
#> [1,]    0    0
#> [2,]    0    0
#> 
#> , , 3
#> 
#>      [,1] [,2]
#> [1,]    0    1
#> [2,]    1    0
grid.raster(arr, interpolate = FALSE)

nr <- nara::array_to_nr(arr)
nr
#>           [,1]      [,2]
#> [1,] -16776961    -65281
#> [2,]    -65536 -16777216
#> attr(,"class")
#> [1] "nativeRaster"
grid.raster(nr, interpolate = FALSE)