# Convert images to/from native raster image format

    library(grid)
    library(nara)

## Create a native raster image

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

## Save/Load native raster images to/from PNG and JPEG

The `{fastpng}`, `{png}` and `{jpeg}` packages allow images to be loaded directly as native raster images.

    png_file <- system.file("image", "deer-1.png", package="nara")
    jpg_file <- system.file("image", "deer-1.jpg", package="nara")

    nr <- fastpng::read_png(png_file, type = 'nativeraster')
    class(nr)
    #> [1] "nativeRaster"
    plot(nr)

    nr <- png::readPNG(png_file, native = TRUE)
    class(nr)
    #> [1] "nativeRaster"
    plot(nr)

    nr <- jpeg::readJPEG(jpg_file, native = TRUE)
    class(nr)
    #> [1] "nativeRaster"
    plot(nr)

These packages will also automatically detect and save native raster images

    fastpng::write_png(nr, "test.png")
    jpeg::writeJPEG(nr, "test.jpg")
    png::writePNG(nr, "test.png")

## Convert a regular R `raster` image to/from native raster image format

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

    nr <- nara::raster_to_nr(ras)
    nr
    #> <nativeRaster> object: rows:2  cols:2
    class(nr)
    #> [1] "nativeRaster"
    plot(nr)

## Convert a regular R `array` image to/from native raster image format

    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
    class(arr)
    #> [1] "array"
    grid.raster(arr, interpolate = FALSE)

    nr <- nara::array_to_nr(arr)
    nr
    #> <nativeRaster> object: rows:2  cols:2
    class(nr)
    #> [1] "nativeRaster"
    plot(nr)