Steve
Steve

Reputation: 101

How do I create a PNG barcode on the fly using Barby?

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?

Upvotes: 2

Views: 755

Answers (1)

Jimmy Theis
Jimmy Theis

Reputation: 448

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.

Upvotes: 3

Related Questions