RMagick can not read remote image

2020-06-01 10:53发布

My env is Linux centos, and use ruby 1.8.7, and the code is here below:

require 'rubygems'
require 'RMagick'
Magick::Image.read("http://image.domain.com/image.darenhui.com/images/random_bg/01.jpg")[0]

it throws error like below:

in `read': no decode delegate for this image format `//image.domain.com/images/random_bg/01.jpg' @ error/constitute.c/ReadImage/532 (Magick::ImageMagickError), 

but if i read from local like:

    require 'rubygems'
    require 'RMagick'
    Magick::Image.read("/local/staticimages/random_bg/01.jpg")[0]

everything is ok. I run identify -list format and see below:

     JPEG* JPEG      rw-   Joint Photographic Experts Group JFIF format (62)
     JPG* JPEG      rw-   Joint Photographic Experts Group JFIF format (62)

but when i test by identity for "http://image.domain.com/image.darenhui.com/images/random_bg/01.jpg" to fail, but success for "/local/staticimages/random_bg/01.jpg"

Can someone give me some clue? thank you in advance.

4条回答
Deceive 欺骗
2楼-- · 2020-06-01 11:20

Magick::Image.read does not support URL links. But you can read the remote image using ruby open method:

 require 'rubygems'
 require 'RMagick'
 require "open-uri"


image = Magick::ImageList.new  
urlimage = open("http://www.jewelinfo4u.com/images/Gallery/ruby.jpg") # Image Remote URL 
image.from_blob(urlimage.read)

# crop = image.crop(10,10,200,300) You can crop this image too
# crop.write('C:/nameofyourNewImage.jpg') If you want to save the image you can use this line in windows 
查看更多
我只想做你的唯一
3楼-- · 2020-06-01 11:21

Fast forward to May 2014, and I'm able to just...

require 'rubygems'
require 'RMagick'
include Magick
image = ImageList.new("http://www.jewelinfo4u.com/images/Gallery/ruby.jpg")

And it just works. Feels good.

(Tested on ImageMagick 6.8.8-9 Q16)

EDIT: Does not seem work on Heroku Cedar stack (ImageMagick 6.5.7-8 2012-08-17 Q16) though. :/

查看更多
别忘想泡老子
4楼-- · 2020-06-01 11:23

As far as I can see Magick::Image.read does NOT support URLs, only files/file handles - see http://www.imagemagick.org/RMagick/doc/image1.html#read where it says that it

Reads all the images from the specified file.

It is implemented by the C function ReadImage which does not support URLs - see the ImageMagick source at line 394 here.

IF you want to open an image from a URL you need to download the image somehow - to a file or a stream... then you can feed that file or stream to Magick...

查看更多
▲ chillily
5楼-- · 2020-06-01 11:24

You can read a file from a url with open-uri, then feed that into Rmagick's Image::from_blob.

Example:

require 'open-uri'
require 'rubygems'
require 'Rmagick'

image_url = 'http://example.com/image.jpg'

image = Magick::Image.from_blob(open(image_url).read).first

Note that you should additionally take care to handle exceptions arising from the open HTTP request. Ie, what happens if you get a 404, or a non-image response?

查看更多
登录 后发表回答