The code generates a QR code and prints it, but It is not working on the Debian Os due to not supporting the imported libraries (win32print, Win32ui).
Can anyone tell me how to run it on the Debian without changing the whole code.
from random import randint
import win32print
import win32ui
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
HORZRES = 8
VERTRES = 10
LOGPIXELSX = 88
LOGPIXELSY = 90
PHYSICALWIDTH = 110
PHYSICALHEIGHT = 111
PHYSICALOFFSETX = 112
PHYSICALOFFSETY = 113
__author__ = 'masoodhussain'
import qrcode
import subprocess
import os
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('Masooddkjfdlfs,kokdfds sddshfhkjshfljsdhkjfdrtyyhtfhfghgh3')
qr.make(fit=True)
"subprocess.call(['lp', 'foo.png'])"
printer_name = win32print.GetDefaultPrinter()
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
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)
ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
scale = min (ratios)
hDC.StartDoc (file_name)
hDC.StartPage ()
dib = ImageWin.Dib (bmp)
scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
x1 = int ((printer_size[0] - scaled_width) / 2)
y1 = int ((printer_size[1] - scaled_height) / 2)
x2 = x1 + scaled_width
y2 = y1 + scaled_height
dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))
hDC.EndPage ()
hDC.EndDoc ()
hDC.DeleteDC ()
when I run the code by removing the unsupported libraries it gives an error on this part: error importing
import qrcode
I am trying to import whole folder for using there other files. In Windows it was working perfectly. Any help would be appreciated.Thanks
This code is equivalent to the code posted in Question.
from random import randint
import cups
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
__author__ = 'masoodhussain'
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=5,
border=2,
)
qr.add_data('localhost:5070productinfo')
qr.make(fit=True)
conn= cups.Connection()
printer_name = conn.getPrinters()
printer_name = printer_name.keys()[0]
printqueuelength = len(conn.getJobs())
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
conn.printFile(printer_name,file_name,"Hello", options ={'media':'25x25mm'})
Important part is the installation of required libraries and changing your media to the required size.
Even if you install qrcode, your code will still fail because of the Windows specific library. You need to check on which system you are working and preferably put the whole print function in a separate function.
Here are some useful links: https://stackoverflow.com/a/1857/2776376 and https://pypi.python.org/pypi/pycups
import platform
if platform.system() = 'Linux':
import libcups
elif platform.system() = 'Windows':
import win32print
import win32ui
else:
print('Unsupported OS. Exiting....')
sys.exit(1)
def my_printer_function():
if platform.system() = 'Linux':
#now call the Linux printer
elif platform.system() = 'Windows':
#use your old Windows code
Related
I am still learning to code in python and I am struggling to code object-oriented way. I have written a code using pytessarct library and with the extracted words I have tried to make a simple detector by using keywords as a filter. I want to redo it in class and object format strictly as a learning exercise. Will be highly grateful if anybody can extend any help. Thank you
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
import os
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from PIL import ImageFilter
import re
img_path = 'C:/Users/RAJ/realtest/'
for i in os.listdir(img_path):
images=Image.open(img_path+'//'+i)
plt.imshow(images)
plt.show()
images_new=images.convert('LA')
im_SHARPEN2 = images_new.filter(filter=ImageFilter.SHARPEN)
extract = pytesseract.image_to_string(im_SHARPEN2, lang = 'eng')
extract2 = pytesseract.image_to_string(images_new,lang = 'eng')
final= extract+extract2
x = re.search(r"INCOME|TAX|Account|GOVT.", final,re.M|re.I)
y = re.search(r"GOVERNMENT|DOB|Male|Female.", final,re.M|re.I)
if x == None and y== None:
print('Not a pan card or adhaar card')
elif type(x)== re.Match:
print('This is a pan card')
else:
print('adhaar card detected')
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
import os
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from PIL import ImageFilter
import re
class is_pan_card():
def __init__(self,path):
self.img_path = path
for i in os.listdir(self.img_path):
images=Image.open(self.img_path+'//'+i)
plt.imshow(images)
plt.show()
images_new=images.convert('LA')
im_SHARPEN2 = images_new.filter(filter=ImageFilter.SHARPEN)
extract = pytesseract.image_to_string(im_SHARPEN2, lang = 'eng')
extract2 = pytesseract.image_to_string(images_new,lang = 'eng')
final= extract+extract2
x = re.search(r"INCOME|TAX|Account|GOVT.", final,re.M|re.I)
y = re.search(r"GOVERNMENT|DOB|Male|Female.", final,re.M|re.I)
if x == None and y== None:
print('Not a pan card or adhaar card')
elif type(x)== re.Match:
print('This is a pan card')
else:
print('adhaar card detected')
is_pan =is_pan_card('C:/Users/RAJ/realtest/')
reportlab ImageReader('url') of PIL library does not work.
my env: Python 3.7.6, Pillow 7.0.0, reportlab 3.5.32 (i tried also different version of PIL and reportlab... same error)
img = ImageReader('https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png')
my error
Cannot open resource "https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
fileName='https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png' identity=[ImageReader#0x119474090 filename='https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png']
Solved...Solution using urls images inside tables on reportlab:
from PIL import Image as pillowImage
from django.core.files.storage import default_storage
from io import BytesIO
from reportlab.platypus import Image
cloud_image = default_storage.open('url') # using s3Storage
img = pillowImage.open(cloud_image)
img_byte_arr = BytesIO()
img.save(img_byte_arr, format=img.format)
result = Image(img_byte_arr, w * cm, h * cm)
....
data1 = [[result]]
t1 = Table(data1, colWidths=(9 * cm))
t1.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'LEFT'),]))
t1.hAlign = 'LEFT'
story.append(t1)
...
I have made def function to call JPG image to display easily but it in not working property. Also I don't want to use urllib2. It says image_file = image_to_PhotoImage(image)
NameError: name 'image' is not defined
Any suggestions? Thank you
from urllib import urlopen
from Tkinter import *
def image_to_PhotoImage(image, width = None, height = None):
# Import the Python Imaging Library, if it exists
try:
from PIL import Image, ImageTk
except:
raise Exception, 'Python Imaging Library has not been installed properly!'
# Import StringIO for character conversions
from StringIO import StringIO
# Convert the raw bytes into characters
image_chars = StringIO(image)
# Open the character string as a PIL image, if possible
try:
pil_image = Image.open(image_chars)
except:
raise Exception, 'Cannot recognise image given to "image_to_Photoimage" function\n' + \
'Confirm that image was downloaded correctly'
# Resize the image, if a new size has been provided
if type(width) == int and type(height) == int and width > 0 and height > 0:
pil_image = pil_image.resize((width, height), Image.ANTIALIAS)
# Return the result as a Tkinter PhotoImage
return ImageTk.PhotoImage(pil_image)
import Tkinter as tk
root = tk.Tk()
url = "http://www.online-image-editor.com//styles/2014/images/example_image.png"
gogo = urlopen(url)
data_stream = gogo.read()
gogo.close()
image_file = image_to_PhotoImage(image1)
label = tk.Label(root, image=image_file, bg='black')
I've seen this question and i followed every step, changing the code to satisfy my requirements, that are Python3, Pillow, and ctypes. The less libraries, the better.
import ctypes
from PIL import ImageGrab, Image
from io import BytesIO
user32 = ctypes.windll.user32
img = ImageGrab.grab()
output = BytesIO()
img.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
user32.OpenClipboard()
user32.EmptyClipboard()
user32.SetClipboardData(user32.CF_DIB, data)
user32.CloseClipboard()
That is the stripped code from my script that, i think, is the same code in the question ported to my requirements. When executed, it should copy the current desktop to the clipboard. I get this instead:
File "C:\Users\Gcq\Documents\python\Screen\Screen.py", line 132, in shot
user32.OpenClipboard()
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
I'm sorry i'm asking such a (probably) easy question here, but i really don't know what is failing, and ctypes is not my thing.
The example uses pywin32, which is Python wrapper around Win32 API that hides some low level details you need to take care yourself of if you want to use ctypes.
Here is how you do it using ctypes, it adds a functionally of creating globally allocated buffer and copy the data into that buffer:
#!python
from PIL import Image
#from cStringIO import StringIO
from io import BytesIO
from ctypes import *
from ctypes.wintypes import *
HGLOBAL = HANDLE
SIZE_T = c_size_t
GHND = 0x0042
GMEM_SHARE = 0x2000
GlobalAlloc = windll.kernel32.GlobalAlloc
GlobalAlloc.restype = HGLOBAL
GlobalAlloc.argtypes = [UINT, SIZE_T]
GlobalLock = windll.kernel32.GlobalLock
GlobalLock.restype = LPVOID
GlobalLock.argtypes = [HGLOBAL]
GlobalUnlock = windll.kernel32.GlobalUnlock
GlobalUnlock.restype = BOOL
GlobalUnlock.argtypes = [HGLOBAL]
CF_DIB = 8
OpenClipboard = windll.user32.OpenClipboard
OpenClipboard.restype = BOOL
OpenClipboard.argtypes = [HWND]
EmptyClipboard = windll.user32.EmptyClipboard
EmptyClipboard.restype = BOOL
EmptyClipboard.argtypes = None
SetClipboardData = windll.user32.SetClipboardData
SetClipboardData.restype = HANDLE
SetClipboardData.argtypes = [UINT, HANDLE]
CloseClipboard = windll.user32.CloseClipboard
CloseClipboard.restype = BOOL
CloseClipboard.argtypes = None
#################################################
image = Image.new("RGB", (200, 200), (255, 0, 0))
#output = StringIO()
output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
hData = GlobalAlloc(GHND | GMEM_SHARE, len(data))
pData = GlobalLock(hData)
memmove(pData, data, len(data))
GlobalUnlock(hData)
OpenClipboard(None)
EmptyClipboard()
SetClipboardData(CF_DIB, pData)
CloseClipboard()
Whew. Apparently the win32clipboard library does simplify some things when compared to ctypes. Your attempt to simply replace one with the other is far from correct.
So I booted up my Windows virtual machine, installed Pillow and rewrote your program, learning from two other answers:
import io
import ctypes
msvcrt = ctypes.cdll.msvcrt
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
from PIL import ImageGrab
img = ImageGrab.grab()
output = io.BytesIO()
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()
CF_DIB = 8
GMEM_MOVEABLE = 0x0002
global_mem = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
global_data = kernel32.GlobalLock(global_mem)
msvcrt.memcpy(ctypes.c_char_p(global_data), data, len(data))
kernel32.GlobalUnlock(global_mem)
user32.OpenClipboard(None)
user32.EmptyClipboard()
user32.SetClipboardData(CF_DIB, global_mem)
user32.CloseClipboard()
Is there a Python library I can use for processing files with chm extension that has similar features as HTML parser or BeautifulSoup?
PyCHM:
http://gnochm.sourceforge.net/pychm.html
I've struggled with PyCHM to create simple thumbnailer extracting cover images from .chm files. Here is the code for all those who find this question in the future:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import chm.chm as chm
from bs4 import BeautifulSoup
from PIL import Image
import urlparse
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
class CHMFile:
def __init__(self, file_name):
self.chmfile = chm.CHMFile()
self.chmfile.LoadCHM(file_name)
def create_thumb(self, out_file):
image = None
area = 0 # cover will propably be the biggest image from home page
iui = self.chmfile.ResolveObject(self.chmfile.home)
home = self.chmfile.RetrieveObject(iui[1])[1] # get home page (as html)
tree = BeautifulSoup(home)
for img in tree.find_all('img'):
src_attr = urlparse.urljoin(self.chmfile.home, img.get('src'))
chm_image = self.chmfile.ResolveObject(src_attr)
png_data = self.chmfile.RetrieveObject(chm_image[1])[1] # get image (as raw data)
png_img = Image.open(StringIO(png_data))
new_width, new_height = png_img.size
new_area = new_width * new_height
if(new_area > area and new_width > 50 and new_height > 50): # to ensure image is at least 50x50
area = new_area
image = png_img
if image:
image.save(out_file, format="PNG")
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print 'Create thumbnail image from an chm file'
print 'Usage: %s INFILE OUTFILE' % sys.argv[0]
else:
chm = CHMFile(sys.argv[1])
chm.create_thumb(sys.argv[2])