如何使用 Barby 即时创建 PNG 条形码?

发布于 2024-12-26 00:09:01 字数 988 浏览 2 评论 0原文

我需要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

几度春秋 2025-01-02 00:09:01

我知道这是一个额外的步骤,但由于您使用的是 Heroku,S3 帐户可能不是坏主意。只要您将数据量控制在 5GB 以下且请求量控制在每月 20,000 个以下,即可免费使用一年。您可以暂时将 png 放在那里,并在一段时间后将其删除。

如果您只是即时使用它并且不想将其缓存或存储在任何地方,则可以设置 Content-Type 标头:

headers 'Content-Type' => 'img/png'

然后直接返回该数据。不过,这需要来自不同的路线,您可以从视图中的 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:

headers 'Content-Type' => 'img/png'

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文