Dealing with Images in R

A walkthrough of dealing with images in R and creating a custom image gallery.

Jimmy Briggs
2021-12-18

While developing and designing software projects in R it is very common to have to deal with various images and the process of manipulating, re-sizing, cropping, and dealing with these images can be a huge pain and waste of time.

Examples of Pain Point with Images

Some examples of the pain points when dealing with images are:

The magick Package

Recently I finally decided to take a gander into the popular magick R library.

This package is a swiss-army-knife for dealing with images in R.

A good place to start is the image_resize function which allows you to resize the dimensions of your images. To add to that, let’s create a function allowing one to:

  1. Read in an image file: magick::image_read
  2. Resize that image: magick::image_resize
  3. Save the image back to file: magick::image_write

HTML Head needs:

<head>

<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.0/css/lightgallery.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightgallery-js/1.4.1-beta.0/js/lightgallery.min.js"></script>

<!-- lightgallery plugins -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lg-fullscreen/1.2.1/lg-fullscreen.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lg-thumbnail/1.2.1/lg-thumbnail.min.js"></script>

</head>

Plus the following CSS customization:

#lightgallery > a > img:hover {
   transform: scale(1.15, 1.15);
   transition: 0.4s ease-in-out;
   cursor: pointer;
}

Result

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Citation

For attribution, please cite this work as

Briggs (2021, Dec. 18). Jim's Docs: Dealing with Images in R. Retrieved from https://jimsdocs.jimbrig.com/posts/2021-12-18-1-dealing-with-images-in-r/

BibTeX citation

@misc{briggs2021dealing,
  author = {Briggs, Jimmy},
  title = {Jim's Docs: Dealing with Images in R},
  url = {https://jimsdocs.jimbrig.com/posts/2021-12-18-1-dealing-with-images-in-r/},
  year = {2021}
}