Otimiza avatares do chat de 1.1MB para 60KB e implementa redimensionamento automático de novos avatares

This commit is contained in:
2026-05-28 19:23:00 +00:00
parent 04e61c97d0
commit 22d2e306d4
6 changed files with 60 additions and 1 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

+51
View File
@@ -0,0 +1,51 @@
import os
import sys
from PIL import Image
def optimize_image(img_path, size=160, backup=False):
if not os.path.exists(img_path):
print(f"Error: {img_path} not found.")
return
src_path = img_path
if backup:
backup_path = img_path + ".orig"
if not os.path.exists(backup_path):
os.rename(img_path, backup_path)
print(f"Backed up original to {backup_path}")
src_path = backup_path
else:
src_path = backup_path
try:
img = Image.open(src_path)
width, height = img.size
print(f"Optimizing {img_path}: Original size {width}x{height}")
# Crop to square
crop_size = min(width, height)
left = (width - crop_size) // 2
if height > width:
top = int((height - crop_size) * 0.15)
else:
top = (height - crop_size) // 2
right = left + crop_size
bottom = top + crop_size
cropped = img.crop((left, top, right, bottom))
resized = cropped.resize((size, size), Image.Resampling.LANCZOS)
# Save as PNG
resized.save(img_path, 'PNG', optimize=True)
print(f"Saved optimized {size}x{size} image to {img_path}")
except Exception as e:
print(f"Error processing image: {e}")
if __name__ == '__main__':
if len(sys.argv) > 1:
optimize_image(sys.argv[1], backup=False)
else:
optimize_image('/root/Apps/Camila/public/assets/camila_prof.png', backup=True)
optimize_image('/root/Apps/Camila/public/assets/kemily.png', backup=True)
+8
View File
@@ -1295,8 +1295,16 @@ app.post('/api/upload-avatar', requireAuth, (req, res) => {
console.error('Erro ao salvar avatar:', err);
return res.status(500).json({ error: 'Erro ao salvar arquivo' });
}
// Otimizar a imagem em segundo plano com Python
const { exec } = require('child_process');
exec(`python3 scratch/optimize_avatars.py "${filePath}"`, (pyErr) => {
if (pyErr) {
console.error('Erro ao otimizar o avatar enviado com Python:', pyErr);
}
return res.json({ success: true, url: `assets/${fileName}` });
});
});
});
// Rota de login (página)