gbarcode生成条形码的代码

51 篇文章 0 订阅

# Uses subprocesses because
  # 1. ImageMagick/RMagick leaks memory,
  #    and doesn't work in a long-running process. The fork makes it safe.
  # 2. The output from the Gbarcode and ImageMagick is often longer than the pipe buffer,
  #    so we have to empty the buffer from another subprocess
  def BarcodeGenerator.get_barcode_image(barcode_string)
    return BarcodeGenerator.get_subprocess_output do
      barcode_generator = BarcodeGenerator.new
      $stdout.write(barcode_generator.get_barcode_image(barcode_string))
    end
  end

  def initialize
    # we do the imports here to protect long-running processes (like mongrel) from ImageMagick's memory leaks
    require 'RMagick'
    require 'gbarcode'
  end

  def get_barcode_image(string_to_encode)
    if string_to_encode.nil?
      string_to_encode = "No string specified"
    end
    string_to_encode = remove_rails_file_extension(string_to_encode)
    eps_barcode = get_barcode_eps(string_to_encode)
    gif_barcode = convert_eps_to_gif(eps_barcode)
    return gif_barcode
  end

  def remove_rails_file_extension(string_to_encode)
    if string_to_encode[-4..-1] == ".png"
      string_to_encode = string_to_encode[0..-5]
    end
    return string_to_encode
  end

  def get_barcode_eps(string_to_encode)
    barcode_object = Gbarcode.barcode_create(string_to_encode)
    Gbarcode.barcode_encode(barcode_object, Gbarcode::BARCODE_128)
    return BarcodeGenerator.get_subprocess_output do
      Gbarcode.barcode_print(barcode_object, $stdout, Gbarcode::BARCODE_OUT_EPS)
    end
  end

  def convert_eps_to_gif(eps_image)
    base64_eps_image = Base64.encode64(eps_image)
    im = Magick::Image::read_inline(base64_eps_image).first
    im.format = "GIF"
    return BarcodeGenerator.get_subprocess_output do
      im.write($stdout)
    end
  end

  # execute a block's code in a subprocess, returning any output
  def BarcodeGenerator.get_subprocess_output()
    data = ""
    IO.popen('-', 'r+') do |child_filehandle|
      if child_filehandle
        begin
          data = child_filehandle.read
        ensure
          child_filehandle.close_write
        end
      else
        yield
      end
    end
    return data
  end
end

注:1. $stdout是rails的标准输出通道

    2. ImageMagick安装的时候一定要配置ghostscript fonts路径,如:./configure --with-gs-font-dir=/usr/share/ghostscript/8.70/Resource/Font ,否则gbarcode生成的条形码文件是.ep或.eps格式的,ImageMagick不能操作,正确配置

gbarcode生成条形码的代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值