본문 바로가기

건승하고있어요/python

파이썬 openCV 로 라벨 프린트 하기 마무리

반응형

1. 프린트 선택코드 추가

2. 글씨 속성 바꾸는 코드 추가

3. 예외처리

4. 로그기록



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import cx_Oracle
import win32print
import win32api
import win32ui
from PIL import Image, ImageWin
import sys
import logging
import logging.handlers
 
 
logger = ''
 
 
def infos_drinks(voca):
    # db 연결
    con = cx_Oracle.connect('아이디/비밀번호@아이피:포트번호/sid')
    cur = con.cursor()
    cur.execute(
            "select outbound_date, pick_box_cd, item_nm, item_cd from lo_dps_d where item_nm like '%" +
            voca + "%' and rownum <= 50")
 
    drink_list = []
 
    for result in cur:
        # 해당 결과 loop돌려 받아오기 
        outbound_date1 = str(result[0]).split()  # 날짜와 시간 분리
        outbound_date = outbound_date1[0]  # 날짜만 받아오기
        pick_box_cd = result[1]  # pick box 코드
        item_nm = result[2]  # item 이름 -> openCV에서 한글이 깨지는 상황
        item_cd = result[3]  # item 코드
 
        # dic에 정보 넣기
        infos = {
            'outbound_date': outbound_date,
            'pick_box_cd': pick_box_cd,
            'item_nm': item_nm,
            'item_cd': item_cd
        }
 
        drink_list.append(infos)
    print(len(drink_list))
    if len(drink_list) == 0:
        print("검색결과가 없습니다.")
        logger.info("검색결과 0")
        sys.exit(1)
 
    print(drink_list)
    select_printer()
    show_image(drink_list)
 
 
# openCV로 이미지화 하는 함수
def show_image(drink_list):
    try:
        # 모두 0으로 되어 있는 빈 Canvas(검정색)
        img = np.zeros((12007933), np.uint8)
        # img 다른 색으로 채우기
        color = tuple(reversed((255255255)))
        img[:] = color
        x = 0
        y = 0
        page = 0
        pages = '0'
 
        while True:
            reply1 = input("테두리와 글자 속성을 변경하시겠습니까?" + "\n" + "1. 예 2. 아니오")
            reply = int(reply1)
            if reply == 1 or reply == 2:
                break
            else:
                print("선택 범위를 벗어났습니다. 다시 입력해주세요.")
 
        if reply == 1:
            print("테두리 색깔을 선택해주세요.")
            tcolor = choose_font_color()
            while True:
                tthick1 = input("테두리 두께를 골라주세요 1, 2, 3 : ")
                tthick = int(tthick1)
                if 0 <= tthick < 6:
                    break
                else:
                    print("선택 범위를 벗어났습니다. 다시 선택해주세요.")
            print("날짜의 색상을 선택해주세요.")
            color1 = choose_font_color()
            print("피킹 박스 색상을 선택해주세요.")
            color2 = choose_font_color()
            print("아이템코드 색상을 선택해주세요.")
            color3 = choose_font_color()
 
            colors = {'tcolor': tcolor,
                      'color_date': color1,
                      'color_pick': color2,
                      'color_item': color3,
                      'tthick': tthick}
        if reply == 2:
            colors = {'tcolor': (000),
                      'color_date': (000),
                      'color_pick': (000),
                      'color_item': (000),
                      'tthick'1}
 
        for i in range(0len(drink_list)):
            make_images(img, drink_list[i], x, y, colors)
            print(drink_list[i])
            if x < 780:
                x += 400
            if x > 780:
                x = 0
                y += 200
            if y > 1200:
                cv2.imwrite('tag_' + pages + '.jpg', img)
                print_tag_image(pages)
                x = 0
                y = 0
                page += 1
                pages = str(page)
                img[:] = color
 
        cv2.imwrite('tag_' + pages + '.jpg', img)
        print_tag_image(pages)
 
    except Exception as e:
        print("잘못 입력하셨습니다."str(e))
        logger.error("테두리두께: 입력오류:  " + str(e))
        sys.exit(1)
 
 
def make_images(img, infos, x, y, colors):
    # 테두리 그리기
    cv2.rectangle(img, (x, y), (x + 390, y + 190), colors['tcolor'], colors['tthick'])
    # 날짜 입력
    cv2.putText(img, infos['outbound_date'], (x + 50, y + 50), cv2.FONT_HERSHEY_SIMPLEX, 1, colors['color_date'], 2)
    # pick box 코드 입력
    cv2.putText(img, infos['pick_box_cd'], (x + 50, y + 100), cv2.FONT_HERSHEY_SIMPLEX, 1, colors['color_pick'], 2)
    # item 코드 입력
    cv2.putText(img, infos['item_cd'], (x + 50, y + 150), cv2.FONT_HERSHEY_SIMPLEX, 1, colors['color_item'], 2)
 
 
def print_tag_image(pages):
    # HORZRES / VERTRES = printable area
 
    HORZRES = 8
    VERTRES = 10
 
    # LOGPIXELS = dots per inch
 
    LOGPIXELSX = 88
    LOGPIXELSY = 90
 
    # PHYSICALWIDTH/HEIGHT = total area
 
    PHYSICALWIDTH = 110
    PHYSICALHEIGHT = 111
 
    # PHYSICALOFFSETX/Y = left / top margin
 
    PHYSICALOFFSETX = 112
    PHYSICALOFFSETY = 113
 
    printer_name = win32print.GetDefaultPrinter()
    file_name = 'tag_' + pages + '.jpg'
 
    hDC = win32ui.CreateDC()
    hDC.CreatePrinterDC(printer_name)
    printable_area = hDC.GetDeviceCaps(HORZRES), hDC.GetDeviceCaps(VERTRES)
    printer_size = hDC.GetDeviceCaps(PHYSICALWIDTH), hDC.GetDeviceCaps(PHYSICALHEIGHT)
    printer_margins = hDC.GetDeviceCaps(PHYSICALOFFSETX), hDC.GetDeviceCaps(PHYSICALOFFSETY)
 
    # 가로가 더 길면 프린트를 가로로 바꿔줘
 
    bmp = Image.open(file_name)
    # if bmp.size[0] > bmp.size[1]:
    #  bmp = bmp.rotate(90)
 
    # size[0]이 가로 size[1]이 세로
    print("bmp.size[0]")
    print(bmp.size[0])
 
    print("bmp.size[1]")
    print(bmp.size[1])
 
    ratios = [1.0 * printable_area[0/ bmp.size[0], 1.0 * printable_area[1/ bmp.size[1]]
    scale = min(ratios)
    print("ratios")
    print(ratios)
 
    print("scale")
    print(scale)
 
    hDC.StartDoc(file_name)
    hDC.StartPage()
 
    dib = ImageWin.Dib(bmp)
    # scaled_width, scaled_height = [int(scale * i) for i in bmp.size]
 
    print("scaled_width")
    # print(scaled_width)
    print("scaled_height")
    # print(scaled_height)
 
    # x1 = int((printer_size[0] - scaled_width) / 2)
    # x1 = int((printer_size[0] - bmp.size[0]) / 10)
    x1 = int((printer_size[0- bmp.size[0]) / 11)
 
    # y1 = int((printer_size[1] - scaled_height) / 2)
    # y1 = int((printer_size[1] - bmp.size[1]) / 15)
    y1 = int((printer_size[1- bmp.size[1]) / 16)
 
    # x2 = x1 + scaled_width
    x2 = x1 + (bmp.size[0* 5)
 
    # y2 = y1 + scaled_height
    y2 = y1 + (bmp.size[1* 5 + 50)
    dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2))
 
    print("x1, y1, x2, y2")
    print(x1, y1, x2, y2)
 
    hDC.EndPage()
    hDC.EndDoc()
    hDC.DeleteDC()
 
 
def select_printer():
    try:
        printer_names = []
        Printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 2)
        for Printer in Printers:
            printer_names.append(Printer['pPrinterName'])
 
        for idx in range(0len(printer_names)):
            print('{}\t{}'.format(idx+1, printer_names[idx]))
 
        while True:
            num1 = input("원하는 프린터의 번호를 입력해 주세요: ")
            num = int(num1)
 
            if 0 < num <= len(printer_names):
                break
            else:
                print("선택 범위를 벗어났습니다. 다시 선택해주세요.")
 
        win32print.SetDefaultPrinter(printer_names[num-1])
        new_printer = win32print.GetDefaultPrinter()
        print("선택하신 프린터는 " + new_printer + "입니다.")
 
    except Exception as e:
        print("잘못 입력하셨습니다."str(e))
        logger.error('프린터 선택: 입력 오류:  ' + str(e))
        sys.exit(1)
 
 
def choose_font_color():
    try:
        color_1 = {'color''흰색''rgb': (255255255)}
        color_2 = {'color''검정색''rgb': (000)}
        color_3 = {'color''빨간색''rgb': (25500)}
        color_4 = {'color''파란색''rgb': (00255)}
        color_5 = {'color''노란색''rgb': (2552550)}
        color_6 = {'color''마젠타핑크''rgb': (2370162)}
 
        color_list = [color_1, color_2, color_3, color_4, color_5, color_6]
        colors = []
        rgbs = []
 
        for i in color_list:
            colors.append(i['color'])
            rgbs.append(i['rgb'])
 
        for i in range(0len(color_list)):
            print('{}\t{}'.format(i + 1, colors[i]))
 
        while True:
            num1 = input("원하시는 색깔을 선택해 주세요: ")
            num = int(num1)
            if 0 < num <= 6:
                break
            else:
                print("범위를 벗어났습니다. 다시 입력해 주세요.")
 
        color1 = rgbs[num - 1]
        print(colors[num-1])
 
    except Exception as e:
        print("잘못 입력하셨습니다."str(e))
        logger.error("색상선택: 입력오류:  " + str(e))
        sys.exit(1)
 
    return color1
 
 
def make_logger():
    logger = logging.getLogger('mylogger')
    logger.setLevel(logging.INFO)
 
    formatter = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s]%(asctime)s > %(message)s')
 
    fileHandler = logging.FileHandler('./myLoggerTest.log')
    streamHandler = logging.StreamHandler()
 
    fileHandler.setFormatter(formatter)
    streamHandler.setFormatter(formatter)
 
    logger.addHandler(fileHandler)
    logger.addHandler(streamHandler)
 
    return logger
 
 
logger = make_logger()
voca = input("검색할 단어를 입력해 주세요: ")
logger.info('검색: ' + voca)
infos_drinks(voca)
 
 
 
 
cs


반응형

'건승하고있어요 > python' 카테고리의 다른 글

크롤러 만든 공익 이야기  (0) 2018.11.30
파이썬 오라클연결  (0) 2018.04.19