|
| 1 | +# GROUP: ADDITIONAL_FEATURES |
| 2 | + |
| 3 | +from aspose.imaging import Image, Color, VectorImage, RemoveBackgroundSettings, SizeF |
| 4 | +from aspose.imaging.imageoptions import VectorRasterizationOptions, PngOptions |
| 5 | +from aspose.imaging.fileformats.png import PngColorType |
| 6 | +from aspose.pycore import as_of, cast, is_assignable |
| 7 | +import os |
| 8 | + |
| 9 | + |
| 10 | +# Initialization |
| 11 | +def get_data_root_dir_local(): |
| 12 | + if 'BASE_DIR' in os.environ: |
| 13 | + return os.environ["BASE_DIR"] |
| 14 | + return "." |
| 15 | + |
| 16 | + |
| 17 | +if 'get_data_root_dir' not in dir(): |
| 18 | + get_data_root_dir = get_data_root_dir_local |
| 19 | + |
| 20 | +if 'get_output_dir' not in dir(): |
| 21 | + get_output_dir = get_data_root_dir_local |
| 22 | + |
| 23 | +data_dir = os.path.join(get_data_root_dir(), 'RemoveBackground') |
| 24 | + |
| 25 | + |
| 26 | +# Utility function |
| 27 | +def remove_background_example(file_name, settings): |
| 28 | + input_file_path = os.path.join(data_dir, file_name) |
| 29 | + out_file_path = os.path.join(get_output_dir(), "output") |
| 30 | + if not os.path.exists(out_file_path): |
| 31 | + os.makedirs(out_file_path) |
| 32 | + |
| 33 | + output_file = os.path.join(out_file_path, file_name + ".png") |
| 34 | + with Image.load(input_file_path) as image: |
| 35 | + options = PngOptions() |
| 36 | + vectors = VectorRasterizationOptions() |
| 37 | + vectors.background_color = Color.transparent |
| 38 | + vectors.page_size = cast(SizeF, image.size) |
| 39 | + options.vector_rasterization_options = vectors |
| 40 | + options.color_type = PngColorType.TRUECOLOR_WITH_ALPHA |
| 41 | + |
| 42 | + if is_assignable(image, VectorImage): |
| 43 | + vector_image = as_of(image, VectorImage) |
| 44 | + vector_image.remove_background(settings) |
| 45 | + |
| 46 | + image.save(output_file, options) |
| 47 | + |
| 48 | + if 'SAVE_OUTPUT' not in os.environ: |
| 49 | + os.remove(output_file) |
| 50 | + |
| 51 | +# Example code: |
| 52 | +# The path to the documents directory. |
| 53 | +file_names = ["golfer.emf"] |
| 54 | + |
| 55 | +obj1 = RemoveBackgroundSettings() |
| 56 | +obj1.detection_level = 30 |
| 57 | +rbs = [ obj1 ] |
| 58 | + |
| 59 | +for i, file_name in enumerate(file_names): |
| 60 | + remove_background_example(file_name, rbs[i]) |
0 commit comments