package workers import ( "context" "fmt" "os" "path/filepath" "github.com/disintegration/imaging" "go.uber.org/zap" ) // ThumbnailJob représente un job de génération de thumbnail type ThumbnailJob struct { InputPath string // Chemin du fichier source OutputPath string // Chemin du fichier thumbnail à générer Width int // Largeur du thumbnail (0 = auto, conserve ratio) Height int // Hauteur du thumbnail (0 = auto, conserve ratio) } // NewThumbnailJob crée un nouveau job de thumbnail func NewThumbnailJob(inputPath, outputPath string, width, height int) *ThumbnailJob { // Valeurs par défaut si non spécifiées if width == 0 { width = 300 // Largeur par défaut } if height == 0 { height = 300 // Hauteur par défaut } return &ThumbnailJob{ InputPath: inputPath, OutputPath: outputPath, Width: width, Height: height, } } // Execute exécute le job de génération de thumbnail func (j *ThumbnailJob) Execute(ctx context.Context, logger *zap.Logger) error { // Vérifier que le fichier source existe if _, err := os.Stat(j.InputPath); os.IsNotExist(err) { return fmt.Errorf("input file does not exist: %s", j.InputPath) } // Créer le répertoire de destination s'il n'existe pas outputDir := filepath.Dir(j.OutputPath) if err := os.MkdirAll(outputDir, 0755); err != nil { return fmt.Errorf("failed to create output directory: %w", err) } // Ouvrir l'image source src, err := imaging.Open(j.InputPath) if err != nil { return fmt.Errorf("failed to open image: %w", err) } // Générer le thumbnail avec l'algorithme Lanczos (qualité élevée) thumbnail := imaging.Resize(src, j.Width, j.Height, imaging.Lanczos) // Déterminer le format de sortie depuis l'extension ext := filepath.Ext(j.OutputPath) // Ajuster l'extension si nécessaire if ext == "" { j.OutputPath = j.OutputPath + ".jpg" ext = ".jpg" } // Sauvegarder le thumbnail (imaging.Save détecte automatiquement le format depuis l'extension) if err := imaging.Save(thumbnail, j.OutputPath); err != nil { return fmt.Errorf("failed to save thumbnail: %w", err) } logger.Info("Thumbnail generated successfully", zap.String("input", j.InputPath), zap.String("output", j.OutputPath), zap.Int("width", j.Width), zap.Int("height", j.Height), ) return nil }