app.py
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 |
import sys from pygments import highlight from pygments.lexers import guess_lexer_for_filename, PythonLexer from pygments.formatters import ImageFormatter from PIL import Image import io import os def code_file_to_image(file_path, output_image_path=None): if not os.path.isfile(file_path): print(f"❌ File not found: {file_path}") return with open(file_path, 'r', encoding='utf-8') as file: code = file.read() try: lexer = guess_lexer_for_filename(file_path, code) except: lexer = PythonLexer() formatter = ImageFormatter( font_name='DejaVu Sans Mono', line_numbers=True, image_format='PNG', style='monokai', line_pad=2 ) img_data = highlight(code, lexer, formatter) image = Image.open(io.BytesIO(img_data)) # Default output name if not provided if not output_image_path: base_name = os.path.splitext(os.path.basename(file_path))[0] output_image_path = f"{base_name}_code.png" image.save(output_image_path) print(f"✅ Code image saved to: {output_image_path}") # Example usage if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python code_to_image.py <file_path>") else: input_path = sys.argv[1] code_file_to_image(input_path) import sys from pygments import highlight from pygments.lexers import guess_lexer_for_filename, PythonLexer from pygments.formatters import ImageFormatter from PIL import Image import io import os def code_file_to_image(file_path, output_image_path=None): if not os.path.isfile(file_path): print(f"❌ File not found: {file_path}") return with open(file_path, 'r', encoding='utf-8') as file: code = file.read() try: lexer = guess_lexer_for_filename(file_path, code) except: lexer = PythonLexer() formatter = ImageFormatter( font_name='DejaVu Sans Mono', line_numbers=False, image_format='PNG', style='monokai', line_pad=5 ) img_data = highlight(code, lexer, formatter) image = Image.open(io.BytesIO(img_data)) # Default output name if not provided if not output_image_path: base_name = os.path.splitext(os.path.basename(file_path))[0] output_image_path = f"{base_name}_code.png" image.save(output_image_path) print(f"✅ Code image saved to: {output_image_path}") # Example usage if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python code_to_image.py <file_path>") else: input_path = sys.argv[1] code_file_to_image(input_path) |