Debian Codegraph @

brother_ql/conversion.py

raw
1 #!/usr/bin/env python
2
3 from __future__ import division, unicode_literals
4 from builtins import str
5
6 import logging
7
8 from PIL import Image
9 import PIL.ImageOps, PIL.ImageChops
10
11 from brother_ql.raster import BrotherQLRaster
12 from brother_ql.devicedependent import label_type_specs, ENDLESS_LABEL, DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL, right_margin_addition
13 from brother_ql import BrotherQLUnsupportedCmd
14 from brother_ql.image_trafos import filtered_hsv
15
16 logger = logging.getLogger(__name__)
17
18 logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING)
19
20 def convert(qlr, images, label, **kwargs):
21 r"""Converts one or more images to a raster instruction file.
22
23 :param qlr:
24 An instance of the BrotherQLRaster class
25 :type qlr: :py:class:`brother_ql.raster.BrotherQLRaster`
26 :param images:
27 The images to be converted. They can be filenames or instances of Pillow's Image.
28 :type images: list(PIL.Image.Image) or list(str) images
29 :param str label:
30 Type of label the printout should be on.
31 :param \**kwargs:
32 See below
33
34 :Keyword Arguments:
35 * **cut** (``bool``) --
36 Enable cutting after printing the labels.
37 * **dither** (``bool``) --
38 Instead of applying a threshold to the pixel values, approximate grey tones with dithering.
39 * **compress**
40 * **red**
41 * **rotate**
42 * **dpi_600**
43 * **hq**
44 * **threshold**
45 """
46 label_specs = label_type_specs[label]
47
48 dots_printable = label_specs['dots_printable']
49 right_margin_dots = label_specs['right_margin_dots']
50 right_margin_dots += right_margin_addition.get(qlr.model, 0)
51 device_pixel_width = qlr.get_pixel_width()
52
53 cut = kwargs.get('cut', True)
54 dither = kwargs.get('dither', False)
55 compress = kwargs.get('compress', False)
56 red = kwargs.get('red', False)
57 rotate = kwargs.get('rotate', 'auto')
58 if rotate != 'auto': rotate = int(rotate)
59 dpi_600 = kwargs.get('dpi_600', False)
60 hq = kwargs.get('hq', True)
61 threshold = kwargs.get('threshold', 70)
62 threshold = 100.0 - threshold
63 threshold = min(255, max(0, int(threshold/100.0 * 255)))
64
65 if red and not qlr.two_color_support:
66 raise BrotherQLUnsupportedCmd('Printing in red is not supported with the selected model.')
67
68 try:
69 qlr.add_switch_mode()
70 except BrotherQLUnsupportedCmd:
71 pass
72 qlr.add_invalidate()
73 qlr.add_initialize()
74 try:
75 qlr.add_switch_mode()
76 except BrotherQLUnsupportedCmd:
77 pass
78
79 for image in images:
80 if isinstance(image, Image.Image):
81 im = image
82 else:
83 try:
84 im = Image.open(image)
85 except:
86 raise NotImplementedError("The image argument needs to be an Image() instance, the filename to an image, or a file handle.")
87
88 if im.mode.endswith('A'):
89 # place in front of white background and get red of transparency
90 bg = Image.new("RGB", im.size, (255,255,255))
91 bg.paste(im, im.split()[-1])
92 im = bg
93 elif im.mode == "P":
94 # Convert GIF ("P") to RGB
95 im = im.convert("RGB" if red else "L")
96 elif im.mode == "L" and red:
97 # Convert greyscale to RGB if printing on black/red tape
98 im = im.convert("RGB")
99
100 if dpi_600:
101 dots_expected = [el*2 for el in dots_printable]
102 else:
103 dots_expected = dots_printable
104
105 if label_specs['kind'] == ENDLESS_LABEL:
106 if rotate not in ('auto', 0):
107 im = im.rotate(rotate, expand=True)
108 if dpi_600:
109 im = im.resize((im.size[0]//2, im.size[1]))
110 if im.size[0] != dots_printable[0]:
111 hsize = int((dots_printable[0] / im.size[0]) * im.size[1])
112 im = im.resize((dots_printable[0], hsize), Image.ANTIALIAS)
113 logger.warning('Need to resize the image...')
114 if im.size[0] < device_pixel_width:
115 new_im = Image.new(im.mode, (device_pixel_width, im.size[1]), (255,)*len(im.mode))
116 new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0))
117 im = new_im
118 elif label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL):
119 if rotate == 'auto':
120 if im.size[0] == dots_expected[1] and im.size[1] == dots_expected[0]:
121 im = im.rotate(90, expand=True)
122 elif rotate != 0:
123 im = im.rotate(rotate, expand=True)
124 if im.size[0] != dots_expected[0] or im.size[1] != dots_expected[1]:
125 raise ValueError("Bad image dimensions: %s. Expecting: %s." % (im.size, dots_expected))
126 if dpi_600:
127 im = im.resize((im.size[0]//2, im.size[1]))
128 new_im = Image.new(im.mode, (device_pixel_width, dots_expected[1]), (255,)*len(im.mode))
129 new_im.paste(im, (device_pixel_width-im.size[0]-right_margin_dots, 0))
130 im = new_im
131
132 if red:
133 filter_h = lambda h: 255 if (h < 40 or h > 210) else 0
134 filter_s = lambda s: 255 if s > 100 else 0
135 filter_v = lambda v: 255 if v > 80 else 0
136 red_im = filtered_hsv(im, filter_h, filter_s, filter_v)
137 red_im = red_im.convert("L")
138 red_im = PIL.ImageOps.invert(red_im)
139 red_im = red_im.point(lambda x: 0 if x < threshold else 255, mode="1")
140
141 filter_h = lambda h: 255
142 filter_s = lambda s: 255
143 filter_v = lambda v: 255 if v < 80 else 0
144 black_im = filtered_hsv(im, filter_h, filter_s, filter_v)
145 black_im = black_im.convert("L")
146 black_im = PIL.ImageOps.invert(black_im)
147 black_im = black_im.point(lambda x: 0 if x < threshold else 255, mode="1")
148 black_im = PIL.ImageChops.subtract(black_im, red_im)
149 else:
150 im = im.convert("L")
151 im = PIL.ImageOps.invert(im)
152
153 if dither:
154 im = im.convert("1", dither=Image.FLOYDSTEINBERG)
155 else:
156 im = im.point(lambda x: 0 if x < threshold else 255, mode="1")
157
158 qlr.add_status_information()
159 tape_size = label_specs['tape_size']
160 if label_specs['kind'] in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL):
161 qlr.mtype = 0x0B
162 qlr.mwidth = tape_size[0]
163 qlr.mlength = tape_size[1]
164 else:
165 qlr.mtype = 0x0A
166 qlr.mwidth = tape_size[0]
167 qlr.mlength = 0
168 qlr.pquality = int(hq)
169 qlr.add_media_and_quality(im.size[1])
170 try:
171 if cut:
172 qlr.add_autocut(True)
173 qlr.add_cut_every(1)
174 except BrotherQLUnsupportedCmd:
175 pass
176 try:
177 qlr.dpi_600 = dpi_600
178 qlr.cut_at_end = cut
179 qlr.two_color_printing = True if red else False
180 qlr.add_expanded_mode()
181 except BrotherQLUnsupportedCmd:
182 pass
183 qlr.add_margins(label_specs['feed_margin'])
184 try:
185 if compress: qlr.add_compression(True)
186 except BrotherQLUnsupportedCmd:
187 pass
188 if red:
189 qlr.add_raster_data(black_im, red_im)
190 else:
191 qlr.add_raster_data(im)
192 qlr.add_print()
193
194 return qlr.data