Improve the following code: import base64 import mimetypes import magic import os from…
- User
Improve the following code:
import base64 import mimetypes
import magic
import os from PIL import Image import pyperclip # For clipboard functionality import subprocess
def img_to_data_uri(image_path): """Converts an image to a data URI and copies it to the clipboard."""
try: # Check if the image file exists if not os.path.exists(image_path): raise FileNotFoundError(f"Image file not found: {image_path}") # Get the image's MIME type mime, _ = mimetypes.guess_type(image_path) # mime = magic.from_file(image_path, mime=True) if mime == "image/svg+xml": # Compress SVG using svgo output_folder = os.path.dirname(image_path) svgo_output_path = os.path.join(output_folder, "compressed.svg") subprocess.run(["powershell", "-Command", f"svgo \"{image_path}\" -o \"{svgo_output_path}\""]) # On Windows image_path = svgo_output_path # Update image path to compressed SVG # Open the image and convert it to a byte array with open(image_path, "rb") as image_file: image_bytes = image_file.read() if mime == "image/svg+xml": os.remove(svgo_output_path) else: print("Error compressing SVG, skipping deletion.") # Encode the image bytes as base64 encoded_string = base64.b64encode(image_bytes).decode("utf-8") # Construct the data URI data_uri = f"data:{mime};base64,{encoded_string}" # Copy the data URI to the clipboard pyperclip.copy(data_uri) print("Image URI copied to clipboard successfully!") except Exception as e: print(f"An error occurred: {e}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.