89 lines
2.2 KiB
Go
89 lines
2.2 KiB
Go
package core
|
|
|
|
import (
|
|
"backend/util"
|
|
"errors"
|
|
"image"
|
|
"image/jpeg"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/disintegration/imaging"
|
|
)
|
|
|
|
func CompressImage(path string, name string) (string, error) {
|
|
// Gathering base folder
|
|
basedir, err := os.Getwd()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
name = name + "_compressed.jpeg"
|
|
basedir = filepath.Join(basedir, ".temp", name)
|
|
|
|
// Creating folder
|
|
if err := os.MkdirAll(".temp", 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(basePath string) {
|
|
picd := GetPictureData()
|
|
count := 0
|
|
start := time.Now()
|
|
for i := range picd {
|
|
path := filepath.Join(basePath, picd[i].Album, picd[i].Name)
|
|
name := strings.TrimSuffix(picd[i].Name, filepath.Ext(picd[i].Name))
|
|
compressed_name, err := CompressImage(path, name)
|
|
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 = "http://localhost:8085/photo_compressed/" + compressed_name
|
|
}
|
|
} else {
|
|
util.Logformatrn(util.INFO, "Compressing %d files...", count)
|
|
picd[i].URLCompressed = "http://localhost:8085/photo_compressed/" + compressed_name
|
|
count++
|
|
}
|
|
}
|
|
if count > 0 {
|
|
elapsed := time.Since(start)
|
|
util.Logformatrn(util.CORRECT, "Compressed %d files in %dms.\n", count, elapsed.Milliseconds())
|
|
}
|
|
}
|