0

I have a column in my R dataframe that contains link to images. eg. https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg

When I try to read it using readJPEG it's giving below error-

"unable to open https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg"

So I tried running it separately to check what's happening and it gives the same error.

readJPEG("https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg")

I'm not sure how to debug this as there's not much detail provided in the error message.

2 Answers 2

3

Since the function takes a raw vector, we can avoid having to write to disk by using readBin to read the jpeg as a raw vector directly from the url, and passing this to readJPEG:

img <- "https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg" |>
  readBin("raw", 1e6) |>
  jpeg::readJPEG() 

Now img is an rgb array, so we can do, for example:

plot(as.raster(img))

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

3

That function does not take URLs.

From ?jpeg::readJPEG:

Usage:

     readJPEG(source, native = FALSE)
     
Arguments:

  source: Either name of the file to read from or a raw vector
          representing the JPEG file content.

  native: determines the image representation - if ‘FALSE’ (the
          default) then the result is an array, if ‘TRUE’ then the
          result is a native raster representation.

Fixed code:

tf <- tempfile(fileext = ".jpeg")
download.file("https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg", tf)
# trying URL 'https://storage.googleapis.com/du-prd/books/images/9781668001226.jpg'
# Content type 'image/jpeg' length 40093 bytes (39 KB)
# ==================================================
# downloaded 39 KB
stuff <- jpeg::readJPEG(tf)
class(stuff)
# [1] "array"
unlink(tf) # if you want/need to clean up the temp file

3 Comments

Shame that even url(url_address) doesn't work :/
@Colombo no, but readJPEG(readBin(url_address, "raw", 1e6))) does.
@AllanCameron Nice one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.