Support for Interrupt Monitor
Contents
[
Hide
]
Support Interrupt Monitor for JPEG and PNG Conversion
This document explains how to support an interrupt for conversion of JPEG and PNG image using Aspose.Imaging. This example uses the Interrupt class to produce an interrupt during conversion.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aspose.pycore as aspycore | |
from aspose.imaging import * | |
from aspose.imaging.brushes import * | |
from aspose.imaging.fileformats.jpeg import * | |
from aspose.imaging.fileformats.png import * | |
from aspose.imaging.imageoptions import * | |
from aspose.imaging.multithreading import * | |
from aspose.imaging.sources import * | |
import os | |
import time | |
from datetime import datetime | |
from threading import Thread | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Tries to convert image from one format to another. Handles interruption. | |
def thread_proc(input_path, output_path, save_options, monitor): | |
print("Work thread") | |
with Image.load(input_path) as image: | |
InterruptMonitor.set_thread_local_instance(monitor) | |
try: | |
image.save(output_path, save_options) | |
print("Finished correctly") | |
except RuntimeError as e: | |
if "OperationInterruptedException" in str(e): | |
print("The save thread #{0} finishes at {1}".format(thread.native_id, datetime.now())) | |
# print(e) | |
finally: | |
InterruptMonitor.set_thread_local_instance(None) | |
save_options = PngOptions() | |
monitor = InterruptMonitor() | |
thread = Thread(target=thread_proc, args=(os.path.join(data_dir, "template.jpg"), os.path.join(data_dir, "result.png"), save_options, monitor)) | |
try: | |
thread.start() | |
# The timeout should be less than the time required for full image conversion (without interruption). | |
time.sleep(0.1) | |
# Interrupt the process | |
monitor.interrupt() | |
print("Interrupting the save thread #{0} at {1}".format(thread.native_id, datetime.now())) | |
# Wait for interruption... | |
thread.join() | |
finally: | |
# If the file to be deleted does not exist, no exception is thrown. | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.png")) | |