如何调整python-barcode(0.15.1)生成条形码的上下边框?
解决python-barcode 0.15.1中ImageWriter添加上下边框的问题
python-barcode的ImageWriter默认会将quiet_zone参数同时应用到条形码的上下左右区域,这就是你看到上下边框的原因——库本身没有暴露单独控制上下边距的选项,所以需要通过自定义Writer类来重写绘制逻辑,直接去掉或调整上下边距,无需后处理PNG。
方案1:完全移除上下边框
自定义继承自ImageWriter的类,修改绘制时的尺寸计算和起始位置,只保留左右的quiet_zone:
import barcode from barcode.writer import ImageWriter class NoTopBottomMarginWriter(ImageWriter): def _paint(self, barcode_writer): # 计算条形码本身的宽高 barcode_width, barcode_height = barcode_writer.calculate_size() # 左右保留quiet_zone,上下边距设为0 total_width = barcode_width + 2 * self.quiet_zone total_height = barcode_height # 创建适配尺寸的画布 self._image = self._draw.Image.new("RGB", (total_width, total_height), self.background) draw = self._draw.Draw(self._image) # 绘制条形码,x轴保留quiet_zone偏移,y轴从0开始 for x, y, width, color in barcode_writer.iter_bars(): draw.rectangle( [ (x + self.quiet_zone, y), (x + width + self.quiet_zone, y + barcode_height), ], fill=color, ) # 使用自定义Writer生成Code39条码 code = barcode.get('code39', 'YOUR_BARCODE_DATA', writer=NoTopBottomMarginWriter()) # 配置参数:quiet_zone控制左右空白,write_text移除下方文本 options = { 'quiet_zone': 5, # 根据需求调整左右空白大小 'write_text': False } # 保存为PNG code.save('barcode_no_top_bottom_margin', options=options)
方案2:自定义上下边距
如果需要保留少量上下空白(而非完全移除),可以给自定义Writer添加上下边距参数,灵活控制:
import barcode from barcode.writer import ImageWriter class CustomMarginWriter(ImageWriter): def __init__(self, upper_margin=0, lower_margin=0, **kwargs): super().__init__(**kwargs) self.upper_margin = upper_margin self.lower_margin = lower_margin def _paint(self, barcode_writer): barcode_width, barcode_height = barcode_writer.calculate_size() # 总宽度=条码宽度+左右quiet_zone,总高度=条码高度+上下边距 total_width = barcode_width + 2 * self.quiet_zone total_height = barcode_height + self.upper_margin + self.lower_margin self._image = self._draw.Image.new("RGB", (total_width, total_height), self.background) draw = self._draw.Draw(self._image) # 绘制条形码时,y轴从upper_margin位置开始 for x, y, width, color in barcode_writer.iter_bars(): draw.rectangle( [ (x + self.quiet_zone, y + self.upper_margin), (x + width + self.quiet_zone, y + barcode_height + self.upper_margin), ], fill=color, ) # 使用自定义上下边距的Writer writer = CustomMarginWriter(upper_margin=2, lower_margin=2) code = barcode.get('code39', 'YOUR_BARCODE_DATA', writer=writer) options = { 'quiet_zone': 5, 'write_text': False } code.save('barcode_custom_margin', options=options)
原理说明
原ImageWriter的_paint方法中,会将quiet_zone同时添加到上下左右的尺寸计算中,并且绘制时上下都偏移quiet_zone距离。通过重写该方法,我们可以单独控制上下方向的空白区域,完全绕过库的默认逻辑,直接生成适配表格的紧凑条形码。
内容的提问来源于stack exchange,提问作者OptiAndrew
相关产品推荐
相关产品推荐

