So this should be pretty easy, yet I can't get it work.
I have a controller method that finds an image based on a query, then the output gets cached. The image could be remote (flickr, google images, etc) or it could be local. Regardless of the source, I just need take the image file contents, and pass it through to the user. In essence, a proxy. Passing through remote images seems to work fine, but passing through local images gives me a:
invalid byte sequence in UTF-8
So here's what I got. I'm hoping someone can solve the problem or guide me in a better direction with my code.
def image_proxy query = params[:query] image_url = get_image_url(query) # returns an absolute local file path or a URL response.headers['Cache-Control'] = "public, max-age=#{12.hours.to_i}" response.headers['Content-Type'] = 'image/jpeg' response.headers['Content-Disposition'] = 'inline' render :text => open(image_url).read end
Remote files work fine, local files don't.
Bonus to anyone that can help solve this other issue:
Thanks!
Rendering is the process involved in the generation of a two-dimensional or three-dimensional image from a model by means of application programs. Rendering is mostly used in architectural designs, video games, and animated movies, simulators, TV special effects and design visualization.
Image rendering allows you to portray your projects even the ones that are being developed in life-like visuals. This helps your prospects and investors not just visualize the layout and architecture but also get a sense of style, space, and design.
Image Rendering In-Camera Whatever device you're taking a photo on has to interpret the data sent to it from the image sensor and then translate that information into a picture. The image you see on your electronic viewfinder and/or LCD screen is your camera's rendering of the scene.
Try using render :text => open(image_url, "rb").read
, which tells Ruby that the file it opens is binary, and not to try reading it as text.
edit
For the bonus question, you could read the first few bytes and look at what they contain. A PNG will always start with the hexadecimal byte values 89 50 4E 47 0D 0A 1A 0A (or the decimal values 137 80 78 71 13 10 26 10).
Wikipedia has a list of magic numbers used to identify file that you can look at. Just create a method of some sort that reads the first few bytes and compares it to that.
What version of Rails? For Rails 3, you should look at the streaming methods that were added. send_data would be the proper way of sending binary data. If the images are local, and your web server supports it, you can use send_file which won't block a rails instance while the user downloads an image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With