package core import ( "backend/util" "errors" "image" "image/jpeg" "os" "path/filepath" "strings" "time" "github.com/disintegration/imaging" ) func CompressImage(path string) (string, error) { name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(filepath.Base(path))) + "_compressed.jpeg" basedir := filepath.Join(util.GetConfig().PhotoPath, ".compressed", name) // Creating folder if err := os.MkdirAll(filepath.Join(util.GetConfig().PhotoPath, ".compressed"), 0755); err != nil { return "", err } // Checking output file if _, err := os.Stat(basedir); err == nil { return name, errors.New("file already created") } // Create file outputFile, err := os.Create(basedir) if err != nil { return "", err } defer outputFile.Close() // Opening image + Reducing its size and quality img, err := imaging.Open(path) if err != nil { return "", err } width := float64(img.Bounds().Dx()) height := float64(img.Bounds().Dy()) ratio := float64(0) var imgOutput *image.NRGBA if width < height { ratio = height / width imgOutput = imaging.Resize(img, 320, int(320*ratio), imaging.Lanczos) } else { ratio = width / height imgOutput = imaging.Resize(img, int(320*ratio), 320, imaging.Lanczos) } // Encoding to jpeg afterwards if err := jpeg.Encode(outputFile, imgOutput, &jpeg.Options{Quality: 100}); err != nil { return "", err } return name, nil } func CompressFiles() { picd := GetPictureData() cfg := util.GetConfig() count := 0 start := time.Now() for i := range picd { path := filepath.Join(cfg.PhotoPath, picd[i].Album, picd[i].Name) compressed_name, err := CompressImage(path) if err != nil { if strings.Compare(err.Error(), "file already created") != 0 { util.Logformat(util.WARNING, "Failed to compress '%s' : (%v)\n", picd[i].Name, err) } else { picd[i].URLCompressed = util.GetURL() + "/.compressed/" + compressed_name } } else { util.Logformatrn(util.INFO, "Compressing %d files...", count) picd[i].URLCompressed = util.GetURL() + "/.compressed/" + compressed_name count++ } } if count > 0 { elapsed := time.Since(start) util.Logformatrn(util.CORRECT, "Compressed %d files in %dms.\n", count, elapsed.Milliseconds()) } }