渲染图像 [英] Rendering an image

查看:117
本文介绍了渲染图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这应该很简单,但我无法让它工作。

So this should be pretty easy, yet I can't get it work.

我有一个控制器方法,可以根据查询查找图像,然后是输出被缓存。图像可以是远程的(flickr,谷歌图像等),也可以是本地的。无论来源如何,我只需要获取图像文件内容,并将其传递给用户。从本质上讲,代理。通过远程图像似乎工作正常,但通过本地图像给我一个:

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:


  1. I需要设置适当的内容类型。远程图像网址不告诉我图像类型,我只是得到一个网址,有时网址不包含扩展名。所以我选择了jpeg,因为无论发送给我的图像类型如何,它似乎都有效。

谢谢!

推荐答案

尝试使用 render:text =>打开(image_url,rb)。读取,告诉Ruby它打开的文件是二进制文件,而不是尝试将其作为文本读取。

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.

编辑

对于红利问题,您可以阅读前几个字节并查看它们包含的内容。
PNG始终以十六进制字节值89 50 4E 47 0D 0A 1A 0A(或十进制值137 80 78 71 13 10 26 10)开头。

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.

这篇关于渲染图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆