Math Avengers
Math Avengers

Reputation: 792

Open image file instead of download the file in R

Suppose I scrape 4 image files from website using httr and rvest, how can I open (not download) the files in a 2x2 matrixes? For example, using the example from this post

I have:

library(rvest); library(dplyr)

url <- "http://www.calacademy.org/explore-science/new-discoveries-an-alaskan-butterfly-a-spider-physicist-and-more"
webpage <- html_session(url)
link.titles <- webpage %>% html_nodes("img")

img.url <- link.titles[13] %>% html_attr("src")

download.file(img.url, "test.jpg", mode = "wb")

But instead of 1 image, I have 4 images and instead of downloading the file, I want to open the images in a 2x2 matrix, like: enter image description here

Edited for comment:

What do you mean by open is displaying the images without creating a temporary intermediary file. This is because there will be thousands of images and I am trying not to overwhelm the computer. What do you mean by display the images is displaying them as a plot.

Upvotes: 1

Views: 461

Answers (1)

Billy34
Billy34

Reputation: 2174

I tried your code but could not manage to get image url so using a fake one (using your's should not be a problem)

# get image as a raw vector (no intermediary file)
library(httr)
img_res <- GET("http://image_site/image_path/image_file.png")
img_type <- http_type(img_res)
img_data <- content(img_res,"raw")

# read image raw content according to image type
if(img_type=="image/png") {
  library(png)
  img <- readPNG(img_data)
} else if(img_type=="image/jpeg") {
  library(jpeg)
  img <- readJPG(img_data)
}

# display it (here I use ggplot2)
library(ggplot2)
library(grid)
qplot(1:10, 1:10, geom="blank") +
  annotation_custom(rasterGrob(img, interpolate=TRUE))

Upvotes: 1

Related Questions