如何在Rails中响应PNG或JPG并从HTML生成图像? [英] How to respond_to PNG or JPG in Rails and generate image from HTML?

查看:171
本文介绍了如何在Rails中响应PNG或JPG并从HTML生成图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找宝石或解决方案以在控制器响应中生成图像.

I am looking for a gem or solution to generate image in controller response.

如果可以在控制器中这样做,那就太好了

It would be nice if it's possible to do in controller like that:

respond_to :html, :png

def show
  ...
  respond_to do |format|
    format.html
    format.png { ??? }  # some html to png converter 
  end
end

当请求png格式时,响应使用模板处理:

When the png format is requested the response handles with template:

#show.png.haml
%h1
  Some title
%p
  Some content

结果应该是一张图片.

我了解pdf生成解决方案 PDFKit

I know about pdf generation solutions PDFKit, prawn and am looking for image generation.

有人知道有效的解决方案/示例吗?任何起点将不胜感激.

Does anybody know working solution/example? Any starting point would be very appreciated.

推荐答案

在此处查看: http://weblog.rubyonrails.org/2006/12/19/using-custom-mime-types

Mime::Type.register "image/png", :png

# then in your controller action
def show
  respond_to do |format|
    format.html { }
    format.png { }
  end
end

UPD

如何生成图像.如果您需要将HTML页面转换为图像.您可以使用wkhtmltoimage

What about image generating. If you need to convert your HTML page into image. You can use wkhtmltoimage
http://code.google.com/p/wkhtmltopdf/downloads/detail?name=wkhtmltoimage-0.10.0_beta2-static-amd64.tar.bz2&can=4&q=

对于wkhtmltopdf,没有像pdfkit这样的宝石,但是它易于使用.

There is no gem like pdfkit for wkhtmltopdf but it is easy to use.

还可以使用pdfKIT gem,然后使用imagemagick将PDF转换为PNG.这也很容易.

Also you can use pdfKIT gem and after that convert PDF to PNG with imagemagick. That is quite easy too.

UPD

我更喜欢使用IMGKit gem

Istead of using SnapShot I prefer to use IMGKit gem

https://github.com/csquared/IMGKit

这篇关于如何在Rails中响应PNG或JPG并从HTML生成图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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