Update the webcame and printing image part
This commit is contained in:
parent
3d8c22598d
commit
38b3acfb89
@ -50,7 +50,7 @@ if os.getenv('LIPY_DEBUG') == True:
|
|||||||
app.secret_key = configuration_file["secrets"]["flask_secret_key"]
|
app.secret_key = configuration_file["secrets"]["flask_secret_key"]
|
||||||
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||||
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
|
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
|
||||||
app.config['MAX_CONTENT_LENGTH'] = 3 * 1000 * 1000 # Maximum 3Mb for a file upload
|
app.config['MAX_CONTENT_LENGTH'] = 10 * 1000 * 1000 # Maximum 3Mb for a file upload
|
||||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||||
|
|
||||||
# Printer connection
|
# Printer connection
|
||||||
|
@ -3,7 +3,8 @@ from flask import flash
|
|||||||
from escpos.printer import Usb, USBNotFoundError
|
from escpos.printer import Usb, USBNotFoundError
|
||||||
from time import sleep, gmtime, strftime
|
from time import sleep, gmtime, strftime
|
||||||
import os.path
|
import os.path
|
||||||
from PIL import Image
|
from PIL import Image, ImageEnhance, ImageOps
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
class Printer(object):
|
class Printer(object):
|
||||||
@ -138,6 +139,12 @@ class Printer(object):
|
|||||||
def print_img(self, path, sign):
|
def print_img(self, path, sign):
|
||||||
clean_signature = str(sign)
|
clean_signature = str(sign)
|
||||||
|
|
||||||
|
if len(clean_signature) > 256 or len(clean_signature) < 3:
|
||||||
|
self.app.logger.warning("Could not print message without a signature.")
|
||||||
|
flash("Could not print message without a signature.",category='error')
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
if not os.path.isfile(str(path)):
|
if not os.path.isfile(str(path)):
|
||||||
self.app.logger.warning("File does not exist : " + str(path))
|
self.app.logger.warning("File does not exist : " + str(path))
|
||||||
flash('The file path for this image :' + str(path) + " wasn't found. Please try again.", 'error')
|
flash('The file path for this image :' + str(path) + " wasn't found. Please try again.", 'error')
|
||||||
@ -145,21 +152,9 @@ class Printer(object):
|
|||||||
else:
|
else:
|
||||||
self.app.logger.debug("Printing file from " + str(path))
|
self.app.logger.debug("Printing file from " + str(path))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.app.logger.debug("Resizing the image")
|
self.app.logger.debug("Proccessing the image")
|
||||||
with Image.open(path) as im:
|
path = process_image(self, path)
|
||||||
|
|
||||||
basewidth = 575
|
|
||||||
img = Image.open(path)
|
|
||||||
wpercent = (basewidth/float(img.size[0]))
|
|
||||||
hsize = int((float(img.size[1])*float(wpercent)))
|
|
||||||
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
|
|
||||||
if img.height > 1000:
|
|
||||||
flash("Image is too long, sorry ! Keep it below 500×1000 pixels.",'error')
|
|
||||||
return False
|
|
||||||
img.save(path)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
flash(str(e))
|
flash(str(e))
|
||||||
self.app.logger.error(str(e))
|
self.app.logger.error(str(e))
|
||||||
@ -178,3 +173,53 @@ class Printer(object):
|
|||||||
self.printer.close()
|
self.printer.close()
|
||||||
flash(str(e),'error')
|
flash(str(e),'error')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def process_image(self, path):
|
||||||
|
brightness_factor = 1.5 # Used only if image is too dark
|
||||||
|
brightness_threshold = 150 # Brightness threshold (0–255)
|
||||||
|
contrast_factor = 0.8 # Less than 1.0 = lower contrast
|
||||||
|
max_width = 575
|
||||||
|
max_height = 1000
|
||||||
|
|
||||||
|
with Image.open(path) as original_img:
|
||||||
|
# Convert to RGB if needed (JPEG doesn't support alpha)
|
||||||
|
if original_img.mode in ("RGBA", "P"):
|
||||||
|
self.app.logger.debug("Converting the image to RGB from RGBA")
|
||||||
|
original_img = original_img.convert("RGB")
|
||||||
|
|
||||||
|
# Resize while maintaining aspect ratio
|
||||||
|
original_img.thumbnail((max_width, max_height), Image.LANCZOS)
|
||||||
|
self.app.logger.debug("Resized the image")
|
||||||
|
|
||||||
|
# Convert to grayscale for dithering
|
||||||
|
dithered_img = original_img.convert("L").convert("1") # Dithering using default method (Floyd–Steinberg)
|
||||||
|
self.app.logger.debug("Dithered the image")
|
||||||
|
|
||||||
|
# Compute brightness of original image (grayscale average)
|
||||||
|
grayscale = original_img.convert("L")
|
||||||
|
avg_brightness = np.array(grayscale).mean()
|
||||||
|
self.app.logger.debug("Average brightness of the image : " + str(avg_brightness) )
|
||||||
|
|
||||||
|
# Dynamically compute brightness factor if too dark
|
||||||
|
if avg_brightness < brightness_threshold:
|
||||||
|
brightness_factor = 1 + (brightness_threshold - avg_brightness) / brightness_threshold
|
||||||
|
brightness_factor = min(max(brightness_factor, 1.1), 2.5) # Clamp between 1.1 and 2.5
|
||||||
|
self.app.logger.debug(f"Image too dark, increasing brightness by a factor of {brightness_factor:.2f}")
|
||||||
|
enhancer = ImageEnhance.Brightness(original_img)
|
||||||
|
original_img = enhancer.enhance(brightness_factor)
|
||||||
|
|
||||||
|
# Reduce contrast
|
||||||
|
contrast_enhancer = ImageEnhance.Contrast(original_img)
|
||||||
|
original_img = contrast_enhancer.enhance(contrast_factor)
|
||||||
|
|
||||||
|
# Final resize check
|
||||||
|
if original_img.height > max_height:
|
||||||
|
flash("Image is too long, sorry! Keep it below 575×1000 pixels.", 'error')
|
||||||
|
self.app.logger.error("Image is too long, sorry! Keep it below 575×1000 pixels.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Convert to JPEG and save
|
||||||
|
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
|
||||||
|
original_img.save(jpeg_path, format='JPEG', quality=95, optimize=True)
|
||||||
|
|
||||||
|
return jpeg_path
|
||||||
|
@ -132,7 +132,7 @@ function print_picture(data){
|
|||||||
// headers:{
|
// headers:{
|
||||||
// 'Content-Type': 'multipart/form-data'
|
// 'Content-Type': 'multipart/form-data'
|
||||||
// }
|
// }
|
||||||
}).then(function(response) { console.log('Success:', response); alert("Picture printed."); } , true)
|
}).then(function(response) { console.log('Success:', response); } , true)
|
||||||
.catch(error => console.error('Error:', error), false);
|
.catch(error => console.error('Error:', error), false);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user