Search code examples
rggplot2pnglatticeico

How to use .ico images in plots programmatically with/without conversion


How to use .ICO image files in plots programmatically with/without conversion?

My question is a follow-up of How to convert .ICO to .PNG?, targeted to R, and with the following specific details:

  • I am not asking about methods involving transcluding the icons within an HTML, e.g. inside a shiny app (author: RStudio). That is of course possible.

  • Can the icons .ICO files be used directly in a base-R plot, a ggplot object (author: Hadley Wickham) , a lattice plot (author: Deepayan Sarkar)? And will this approach be robust to printing the output to PDF?

  • How to convert the ICO icons to PNG with or without a dedicated R library. This method would be careful to handle the icon's image size, depth, transparency, and other potentially important properties.

The motivation for this is simply that there are many open-source libraries of icons that one could use inside plot objects, e.g. Inserting an image to ggplot2, Display custom image as geom_point, Inserting an image to ggplot outside the chart area.

In the question I cite at the top, How to convert .ICO to .PNG?, there are examples of code in C# and in Python, but none in R.


Solution

  • There is now a magick package and you don't need to use system anymore:

    library(magick)
    path  <- "magic.png" # wherever you want to save
    image <- image_read("https://rpubs.com/favicon.ico") # works with local path as well
    

    In R studio, this will print our image in the plot window, for ico files it shows the different icons available in the file.

    image 
    

    Then you can save in the desired format :

    image_write(image,path,"png")
    file.exists(path)
    # [1] TRUE
    

    There's a really cool vignette: