changeimage / app.py
Merlintxu's picture
Update app.py
5c60085 verified
raw
history blame
5.99 kB
import gradio as gr
from PIL import Image
import os
import tempfile
import pyheif
import ntpath
def open_heic_image(image_path):
heif_file = pyheif.read(image_path)
img = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
heif_file.mode,
heif_file.stride,
)
return img
def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_quality):
# Obtener el nombre del archivo original sin la extensi贸n
original_filename = ntpath.basename(image.name)
base_name, ext = os.path.splitext(original_filename)
# Manejar archivos HEIC
if image.name.lower().endswith(".heic"):
img = open_heic_image(image.name)
else:
img = Image.open(image)
# Convertir la imagen a RGB si est谩 en RGBA o en un modo no soportado por JPEG
if img.mode not in ['RGB', 'L']:
img = img.convert('RGB')
original_size = os.path.getsize(image.name) / 1024 # tama帽o en KB
output_dir = "/tmp/optimized_images"
os.makedirs(output_dir, exist_ok=True)
# Lista para almacenar los resultados
results = []
# Optimizaci贸n para PNG
if png_optimize:
lossless_output_path = os.path.join(output_dir, f"{base_name}-lossless.png")
img.save(lossless_output_path, format="PNG", optimize=True)
lossless_size = os.path.getsize(lossless_output_path) / 1024
percent_reduction = 100 * (original_size - lossless_size) / original_size
results.append((Image.open(lossless_output_path), f"PNG: {lossless_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", lossless_output_path))
# Optimizaci贸n para JPEG
lossy_output_path = os.path.join(output_dir, f"{base_name}-lossy.jpg")
img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
lossy_size = os.path.getsize(lossy_output_path) / 1024
percent_reduction = 100 * (original_size - lossy_size) / original_size
results.append((Image.open(lossy_output_path), f"JPEG: {lossy_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", lossy_output_path))
# Reducci贸n de resoluci贸n (JPEG)
reduced_output_path = os.path.join(output_dir, f"{base_name}-reduced_resolution.jpg")
new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
reduced_img = img.resize(new_resolution, Image.LANCZOS)
reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
reduced_size = os.path.getsize(reduced_output_path) / 1024
percent_reduction = 100 * (original_size - reduced_size) / original_size
results.append((Image.open(reduced_output_path), f"JPEG (resoluci贸n reducida): {reduced_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", reduced_output_path))
# Optimizaci贸n para WebP
webp_lossy_output_path = os.path.join(output_dir, f"{base_name}-lossy.webp")
img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
percent_reduction = 100 * (original_size - webp_lossy_size) / original_size
results.append((Image.open(webp_lossy_output_path), f"WebP: {webp_lossy_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", webp_lossy_output_path))
# Asegurarse de que todos los resultados est谩n presentes (4 entradas)
while len(results) < 4:
results.append((None, "", None))
# Dividir los resultados en im谩genes, textos y rutas para descarga
outputs = []
for result in results:
outputs.extend(result)
return outputs
with gr.Blocks() as demo:
with gr.Tab("Optimizaci贸n Tradicional"):
image_input = gr.File(label="Sube tu imagen", file_types=['image', '.heic'])
optimize_button = gr.Button("Optimizar")
with gr.Row():
with gr.Column():
optimized_output1 = gr.Image(label="Optimizaci贸n sin p茅rdida")
png_optimize = gr.Checkbox(label="Optimizar PNG", value=True)
download_button1 = gr.File(label="Descargar", visible=True)
optimized_size1 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output2 = gr.Image(label="Optimizaci贸n con p茅rdida (JPEG)")
jpeg_quality = gr.Slider(label="Calidad JPEG", minimum=10, maximum=100, value=75, step=1)
download_button2 = gr.File(label="Descargar", visible=True)
optimized_size2 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output3 = gr.Image(label="Reducci贸n de resoluci贸n (JPEG)")
jpeg_resolution = gr.Slider(label="Resoluci贸n JPEG (%)", minimum=10, maximum=100, value=75, step=1)
download_button3 = gr.File(label="Descargar", visible=True)
optimized_size3 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output4 = gr.Image(label="Optimizaci贸n WebP con p茅rdida")
webp_quality = gr.Slider(label="Calidad WebP", minimum=10, maximum=100, value=75, step=1)
download_button4 = gr.File(label="Descargar", visible=True)
optimized_size4 = gr.Text(value="", interactive=False, show_label=False)
# Conectar cada control a la funci贸n de optimizaci贸n
optimize_button.click(
fn=optimize_image,
inputs=[image_input, png_optimize, jpeg_quality, jpeg_resolution, webp_quality],
outputs=[
optimized_output1, optimized_size1, download_button1,
optimized_output2, optimized_size2, download_button2,
optimized_output3, optimized_size3, download_button3,
optimized_output4, optimized_size4, download_button4
]
)
demo.launch()