如何使用 Barby 即时创建 PNG 条形码?
我需要使用 Barby 生成条形码 png/image
,然后显示图像在一个视图中。
我可以创建一个像这样的条形码 PNG 图像 Barby::Code39.new("STRING", true).to_png
它会返回一个类似以下的字符串:
\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x03`\x00\x00\x00x\x01\x00\x00\
\xD0Mj\x83@\x00\xC5\xF1\x92\xBB\x98\xA2\x90\xEE\xDA;\xE8\xC4,Fi\xC8\x98m\v
D\xAE\x01\xA5\xF10)^\xC2E\xF2\xDE\xFA\x0F?x\xB3\xEB\x84\x9B=L8`\xC0\x80M\x
8\xAF\x15\x0F\x997\x88\xBC-\xE7\xA9\x8C\b\xDF:u\x7F\xFEl\xD4^F\xD6\x989}[\
\xEBL\x8A\x15\x0F<oX\xAE\xDB\xEC}\xCC\xC2\xC4[\xDE\xF4\x8D\xC0\x80\x01\x03
80\x01\x03\x06\f\x180`\xC0\x80\x01\x03\x06\f\x180`\xC0\x80\x01\x03\x06\f\x
CD\xD0\xA2\xAF\xC7$\x15\x85\xC6|\xD3\xBD\x844V\xC9\xAE\xB2\xF5\xC5\x9BE64n
由于我使用 Heroku/Sinatra,因此可以创建文件 t = Tempfile.new("temp"); t.write ...
但是当我在视图中调用 t.path
时,我得到类似 /tmp/qimst7
的内容,当然它是一个 404
错误。
如何在视图中显示 PNG 图像?
I need to generate a barcode png/image
using Barby, and then show the image in a view.
I can create a barcode PNG image like this Barby::Code39.new("STRING", true).to_png
Which returns a string like:
\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x03`\x00\x00\x00x\x01\x00\x00\
\xD0Mj\x83@\x00\xC5\xF1\x92\xBB\x98\xA2\x90\xEE\xDA;\xE8\xC4,Fi\xC8\x98m\v
D\xAE\x01\xA5\xF10)^\xC2E\xF2\xDE\xFA\x0F?x\xB3\xEB\x84\x9B=L8`\xC0\x80M\x
8\xAF\x15\x0F\x997\x88\xBC-\xE7\xA9\x8C\b\xDF:u\x7F\xFEl\xD4^F\xD6\x989}[\
\xEBL\x8A\x15\x0F<oX\xAE\xDB\xEC}\xCC\xC2\xC4[\xDE\xF4\x8D\xC0\x80\x01\x03
80\x01\x03\x06\f\x180`\xC0\x80\x01\x03\x06\f\x180`\xC0\x80\x01\x03\x06\f\x
CD\xD0\xA2\xAF\xC7$\x15\x85\xC6|\xD3\xBD\x844V\xC9\xAE\xB2\xF5\xC5\x9BE64n
Since I'm using Heroku/Sinatra, it's possible to create the file with t = Tempfile.new("temp"); t.write ...
but when I call t.path
in the view I get something like /tmp/qimst7
, and of course it's a 404
error.
How do I show the PNG image in the view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道这是一个额外的步骤,但由于您使用的是 Heroku,S3 帐户可能不是坏主意。只要您将数据量控制在 5GB 以下且请求量控制在每月 20,000 个以下,即可免费使用一年。您可以暂时将 png 放在那里,并在一段时间后将其删除。
如果您只是即时使用它并且不想将其缓存或存储在任何地方,则可以设置
Content-Type
标头:然后直接返回该数据。不过,这需要来自不同的路线,您可以从视图中的
img
标记引用该路线。I know it's an extra step, but since you're using Heroku, an S3 account might not be a bad idea. It's free for a year as long as you keep your data under 5GB and your requests under 20,000/month. You could just drop the png there temporarily and delete it after a certain period of time.
If you're just using it on the fly and don't want to cache or store it anywhere, you may be able to set the
Content-Type
header:and then return that data directly. This would need to be from a different route, though, which you would reference from an
img
tag in your view.