Overview

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(fastpng)

{fastpng} reads and writes PNG images.

{fastpng} exposes configuration options so that the user can make a trade-off between speed of writing and PNG size. These options include:

For example, writing uncompressed PNG images can be 100x faster than writing with regular compression settings.

fastpng uses libspng - current v0.7.4

Features

Supported image data in R

Supported images each have examples in the test_image as part of this package.

Supported PNG image types

Comparison to standard {png} library

| | {fastpng} | {png} | |:------------|-----------------|---------------| | Numeric arrays | Yes | Yes | | Native rasters | Yes | Yes | | Rasters | Yes | | | Integer Arrays | Yes | | | Indexed PNGs | Yes | | | tRNS transparency | Yes | | | Configurable compression | Yes | | | Configurable filtering | Yes | | | Configurable transposition | Yes | |

Compression Settings: Speed / size tradeoff

The following graph shows the speed of writing and the compression ratio for various settings in fastpng. A data point for the png package is also shown.

Example: Read a PNG into R

library(fastpng)
png_file <- system.file("img", "Rlogo.png", package="png")
fastpng::get_png_info(png_file)

ras <- fastpng::read_png(png_file, type = 'raster') 
grid::grid.raster(ras, interpolate = FALSE)

Read as a raster (of hex colours)

ras <- fastpng::read_png(png_file, type = "raster")
ras[7:11, 79:83]

Read as a numeric array

ras <- fastpng::read_png(png_file, type = "array")
ras[7:11, 79:83, 1] # red channel

Read as an integer array

ras <- fastpng::read_png(png_file, type = "array", array_type = 'integer')
ras[7:11, 79:83, 1] # red channel

Read as a native raster

im <- fastpng::read_png(png_file, type = "nativeraster")
im[7:11, 79:83]

Write an image to PNG with/without compression

png_file <- tempfile()
fastpng::write_png(im, png_file)  # standard compression
file.size(png_file)
fastpng::write_png(im, png_file, compression_level = 0) # no compression, but fast!
file.size(png_file)

Write integer matrix as indexed PNG

indices <- test_image$indexed$integer_index
palette <- test_image$indexed$palette

dim(indices)
indices[1:10, 1:10]
palette[1:10]
tmp <- tempfile()
fastpng::write_png(image = indices, palette = palette, file = tmp)
fastpng::write_png(image = indices, palette = palette) |>
  fastpng::read_png() |> 
  grid::grid.raster()


Try the fastpng package in your browser

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

fastpng documentation built on April 3, 2025, 10:01 p.m.