toretore / barby

The Ruby barcode generator
http://toretore.github.com/barby/
MIT License
844 stars 169 forks source link

barcode image tag #75

Closed martinemde closed 7 years ago

martinemde commented 7 years ago

I wrote a simple method that can create an image tag in rails for a barcode based on a requested width and height. Is this something that would make sense in barby?

    def barcode_image_tag(text, height:, width:, margin: 10)
      barcode = Barby::Code39.new(text.to_s)

      # How wide should the bar be so that it best fills the requested image width?
      xdim = (width.to_f / barcode.encoding.length).round

      image = barcode.to_image(
        xdim: xdim * 2, # double resolution for clearer printed image (and retina)
        margin: margin,
        height: (height - margin) * 2 # Barby expects height without top/bottom margin.
      )

      # Now use the official height and width of the image rather than stretch it.
      image_tag(
        image.to_data_url,
        width: image.width / 2,
        height: image.height / 2,
        alt: text.to_s
      )
    end

If this steps outside of the scope of this gem, feel free to close this.

toretore commented 7 years ago

I think this is outside of the scope for barby, but you might want to add it to the wiki (there's an Examples page) or somewhere else that people can find it.