Hatkat

ComprimirImagenTxt

Aug 22nd, 2023
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import base64
  2. from PIL import Image
  3.  
  4. def encode_image(image_path):
  5.     with open(image_path, "rb") as image_file:
  6.         image_data = image_file.read()
  7.         encoded_data = base64.b64encode(image_data)
  8.         return encoded_data.decode("utf-8")
  9.  
  10. def decode_image(encoded_data, output_path):
  11.     decoded_data = base64.b64decode(encoded_data)
  12.     with open(output_path, "wb") as output_file:
  13.         output_file.write(decoded_data)
  14.  
  15. def main():
  16.     while True:
  17.         print("1. Comprimir imagen")
  18.         print("2. Descomprimir imagen")
  19.         print("3. Salir")
  20.        
  21.         choice = input("Selecciona una opción: ")
  22.        
  23.         if choice == "1":
  24.             image_path = input("Ingresa la ruta de la imagen: ")
  25.             encoded_image = encode_image(image_path)
  26.             output_path = input("Ingresa el nombre del archivo de salida (con extensión .txt): ")
  27.            
  28.             with open(output_path, "w") as text_file:
  29.                 text_file.write(encoded_image)
  30.                
  31.             print("Imagen comprimida y guardada como texto.")
  32.        
  33.         elif choice == "2":
  34.             input_path = input("Ingresa la ruta del archivo de texto: ")
  35.             output_path = input("Ingresa el nombre del archivo de salida (con extensión compatible): ")
  36.            
  37.             with open(input_path, "r") as text_file:
  38.                 encoded_image = text_file.read()
  39.            
  40.             decode_image(encoded_image, output_path)
  41.             print("Imagen descomprimida y guardada.")
  42.        
  43.         elif choice == "3":
  44.             break
  45.        
  46.         else:
  47.             print("Opción no válida. Por favor, selecciona una opción válida.")
  48.  
  49. if __name__ == "__main__":
  50.     main()
  51.  
Add Comment
Please, Sign In to add comment