Search code examples
arraysimageiojuliahttp-get

Julia download image from URL directly into memory


I want to download this image from the web. Is there a way in Julia to to avoid downloading the file to disk then loading it back in, and load it straight into memory?? Example: https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png

Currently I could do this, which needs me to write the data to disk, then load it back into memory:

Using Images
Using HTTP
download("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", "google.png")
img = load("google.png")

julia> typeof(img)
Array{RGB{Normed{UInt8,8}},2}

I can see that the type I'm expecting is an array of RGB values

However if I try to make the request directly with HTTP, i get a single vector, that doesn't seem to be readily converted into the image array format

r = HTTP.get("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")

julia> r.body
13504-element Array{UInt8,1}:
 0x89
 0x50
 0x4e
 0x47
 0x0d
 0x0a
 0x1a
    ⋮
 0x45
 0x4e
 0x44
 0xae
 0x42
 0x60
 0x82

What's the best way to get this image data into the correct image format directly?


Solution

  • This has been programmed in ImageMagick.jl

    Setup:

    using HTTP, ImageMagick
    r = HTTP.get("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")
    buffer = IOBuffer(r.body)
    

    Parse:

    julia> ImageMagick.load(buffer)
    184×544 Array{RGBA{N0f8},2} with eltype ColorTypes.RGBA{FixedPointNumbers.Normed{UInt8,8}}:
     RGBA{N0f8}(0.0,0.0,0.0,0.0)        …          RGBA{N0f8}(0.0,1.0,1.0,0.0)
    ...