Otimiza avatares do chat de 1.1MB para 60KB e implementa redimensionamento automático de novos avatares
This commit is contained in:
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 |
@@ -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)
|
||||
@@ -1295,7 +1295,15 @@ 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' });
|
||||
}
|
||||
return res.json({ success: true, url: `assets/${fileName}` });
|
||||
|
||||
// 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}` });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user