渲染图像

编程入门 行业动态 更新时间:2024-10-28 09:21:14
本文介绍了渲染图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

  • 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.

    更多推荐

    渲染图像

    本文发布于:2023-10-30 01:23:57,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1541351.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:图像

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!