2022-08-12 06:03:06 +00:00
|
|
|
package photo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"image"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
|
|
|
"io"
|
|
|
|
"os"
|
2022-08-13 06:11:36 +00:00
|
|
|
"path/filepath"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2022-08-12 06:03:06 +00:00
|
|
|
|
2022-08-26 04:21:46 +00:00
|
|
|
"code.nonshy.com/nonshy/website/pkg/config"
|
|
|
|
"code.nonshy.com/nonshy/website/pkg/log"
|
|
|
|
"code.nonshy.com/nonshy/website/pkg/models"
|
2022-08-12 06:03:06 +00:00
|
|
|
"github.com/edwvee/exiffix"
|
|
|
|
"golang.org/x/image/draw"
|
|
|
|
)
|
|
|
|
|
|
|
|
type UploadConfig struct {
|
|
|
|
User *models.User
|
|
|
|
Extension string // 'jpg' or 'png' only.
|
|
|
|
Data []byte
|
|
|
|
Crop []int // x, y, w, h
|
|
|
|
}
|
|
|
|
|
|
|
|
// UploadPhoto handles an incoming photo to add to a user's account.
|
|
|
|
//
|
|
|
|
// Returns:
|
|
|
|
// - NewFilename() of the created photo file on disk.
|
|
|
|
// - NewFilename() of the cropped version, or "" if not cropping.
|
|
|
|
// - error on errors
|
|
|
|
func UploadPhoto(cfg UploadConfig) (string, string, error) {
|
|
|
|
// Validate and normalize the extension.
|
2023-06-26 06:03:41 +00:00
|
|
|
var (
|
|
|
|
extension = strings.ToLower(cfg.Extension)
|
|
|
|
dbExtension = extension
|
|
|
|
)
|
2022-08-23 02:29:48 +00:00
|
|
|
switch extension {
|
2023-07-22 18:51:58 +00:00
|
|
|
case ".jpg", ".jpe", ".jpeg":
|
2022-08-12 06:03:06 +00:00
|
|
|
extension = ".jpg"
|
2023-07-22 18:51:58 +00:00
|
|
|
dbExtension = ".jpg"
|
2022-08-12 06:03:06 +00:00
|
|
|
case ".png":
|
|
|
|
extension = ".png"
|
2023-06-26 06:03:41 +00:00
|
|
|
dbExtension = ".jpg"
|
2023-06-26 05:55:07 +00:00
|
|
|
case ".gif":
|
2023-06-26 06:03:41 +00:00
|
|
|
extension = ".gif"
|
|
|
|
dbExtension = ".mp4"
|
2022-08-12 06:03:06 +00:00
|
|
|
default:
|
|
|
|
return "", "", errors.New("unsupported image extension, must be jpg or png")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decide on a filename for this photo.
|
|
|
|
var (
|
2023-06-26 06:03:41 +00:00
|
|
|
filename = NewFilename(dbExtension)
|
|
|
|
cropFilename = NewFilename(dbExtension)
|
2022-08-12 06:03:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Decode the image using exiffix, which will auto-rotate jpeg images
|
|
|
|
// based on their EXIF tags.
|
|
|
|
reader := bytes.NewReader(cfg.Data)
|
|
|
|
origImage, _, err := exiffix.Decode(reader)
|
|
|
|
if err != nil {
|
|
|
|
return "", "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the config to get the image width.
|
|
|
|
reader.Seek(0, io.SeekStart)
|
2022-08-13 06:11:36 +00:00
|
|
|
var width, height = origImage.Bounds().Max.X, origImage.Bounds().Max.Y
|
2022-08-12 06:03:06 +00:00
|
|
|
|
|
|
|
// Find the longest edge, if it's too large (over 1280px)
|
|
|
|
// cap it to the max and scale the other dimension proportionally.
|
2022-08-13 06:11:36 +00:00
|
|
|
log.Debug("UploadPhoto: taking a w=%d by h=%d image to name it %s", width, height, filename)
|
2022-08-12 06:03:06 +00:00
|
|
|
if width >= height {
|
2022-08-13 06:11:36 +00:00
|
|
|
log.Debug("Its width(%d) is >= its height (%d)", width, height)
|
2022-08-12 06:03:06 +00:00
|
|
|
if width > config.MaxPhotoWidth {
|
|
|
|
newWidth := config.MaxPhotoWidth
|
2022-08-13 06:11:36 +00:00
|
|
|
log.Debug("\tnewWidth=%d", newWidth)
|
|
|
|
log.Debug("\tnewHeight=(%d / %d) * %d", width, height, newWidth)
|
2022-08-12 06:03:06 +00:00
|
|
|
height = int((float64(height) / float64(width)) * float64(newWidth))
|
|
|
|
width = newWidth
|
2022-08-13 06:11:36 +00:00
|
|
|
log.Debug("Its longest is width, scale to %dx%d", width, height)
|
2022-08-12 06:03:06 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if height > config.MaxPhotoWidth {
|
|
|
|
newHeight := config.MaxPhotoWidth
|
|
|
|
width = int((float64(width) / float64(height)) * float64(newHeight))
|
|
|
|
height = newHeight
|
2022-09-27 02:41:07 +00:00
|
|
|
log.Debug("Its longest is height, scale to %dx%d", width, height)
|
2022-08-12 06:03:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Scale the image.
|
|
|
|
scaledImg := Scale(origImage, image.Rect(0, 0, width, height), draw.ApproxBiLinear)
|
|
|
|
|
|
|
|
// Write the image to disk.
|
2023-06-26 05:55:07 +00:00
|
|
|
if err := ToDisk(filename, extension, scaledImg, &cfg); err != nil {
|
2022-08-12 06:03:06 +00:00
|
|
|
return "", "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Are we producing a cropped image, too?
|
|
|
|
log.Error("Are we to crop? %+v", cfg.Crop)
|
|
|
|
if cfg.Crop != nil && len(cfg.Crop) >= 4 {
|
|
|
|
log.Debug("Also cropping this image to %+v", cfg.Crop)
|
|
|
|
var (
|
|
|
|
x = cfg.Crop[0]
|
|
|
|
y = cfg.Crop[1]
|
|
|
|
w = cfg.Crop[2]
|
|
|
|
h = cfg.Crop[3]
|
|
|
|
)
|
2023-07-22 18:51:58 +00:00
|
|
|
croppedImg, err := Crop(origImage, x, y, w, h)
|
|
|
|
if err != nil {
|
|
|
|
// Error during the crop: return it and just the original image filename
|
|
|
|
log.Error("Couldn't crop new profile photo: %s", err)
|
|
|
|
return filename, "", nil
|
|
|
|
}
|
2022-08-12 06:03:06 +00:00
|
|
|
|
|
|
|
// Write that to disk, too.
|
|
|
|
log.Debug("Writing cropped image to disk: %s", cropFilename)
|
2023-06-26 05:55:07 +00:00
|
|
|
if err := ToDisk(cropFilename, extension, croppedImg, &cfg); err != nil {
|
2023-07-22 18:51:58 +00:00
|
|
|
log.Error("Couldn't write cropped photo to disk: %s", err)
|
|
|
|
return filename, "", nil
|
2022-08-12 06:03:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return both filenames!
|
|
|
|
return filename, cropFilename, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Not cropping, return only the first filename.
|
|
|
|
return filename, "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Scale down an image. Example:
|
|
|
|
//
|
|
|
|
// scaled := Scale(src, image.Rect(0, 0, 200, 200), draw.ApproxBiLinear)
|
|
|
|
func Scale(src image.Image, rect image.Rectangle, scale draw.Scaler) image.Image {
|
|
|
|
dst := image.NewRGBA(rect)
|
2022-08-13 06:11:36 +00:00
|
|
|
copyRect := image.Rect(
|
|
|
|
rect.Min.X,
|
|
|
|
rect.Min.Y,
|
|
|
|
rect.Min.X+rect.Max.X,
|
|
|
|
rect.Min.Y+rect.Max.Y,
|
|
|
|
)
|
|
|
|
scale.Scale(dst, copyRect, src, src.Bounds(), draw.Over, nil)
|
2022-08-12 06:03:06 +00:00
|
|
|
return dst
|
|
|
|
}
|
|
|
|
|
|
|
|
// Crop an image, returning the new image. Example:
|
|
|
|
//
|
|
|
|
// cropped := Crop()
|
2023-07-22 18:51:58 +00:00
|
|
|
func Crop(src image.Image, x, y, w, h int) (image.Image, error) {
|
|
|
|
// Sanity check the crop constraints, e.g. sometimes the front-end might send "203 -1 738 738" with a negative x/y value
|
|
|
|
if x < 0 {
|
|
|
|
log.Debug("Crop(%d, %d, %d, %d): x value %d too low, cap to zero", x, y, w, h, x)
|
|
|
|
x = 0
|
|
|
|
}
|
|
|
|
if y < 0 {
|
|
|
|
log.Debug("Crop(%d, %d, %d, %d): y value %d too low, cap to zero", x, y, w, h, y)
|
|
|
|
y = 0
|
|
|
|
}
|
|
|
|
if x+w > src.Bounds().Dx() {
|
|
|
|
log.Debug("Crop(%d, %d, %d, %d): width is too wide", x, y, w, h)
|
|
|
|
w = src.Bounds().Dx() - x
|
|
|
|
}
|
|
|
|
if y+h > src.Bounds().Dy() {
|
|
|
|
log.Debug("Crop(%d, %d, %d, %d): height is too tall", x, y, w, h)
|
|
|
|
h = src.Bounds().Dy() - y
|
|
|
|
}
|
|
|
|
|
|
|
|
// If they are trying to crop a 0x0 image, return an error.
|
|
|
|
if w == 0 || h == 0 {
|
|
|
|
return nil, errors.New("can't crop to a 0x0 resolution image")
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("Crop(): running draw.Copy with dimensions %d, %d, %d, %d", x, y, w, h)
|
2022-08-13 06:11:36 +00:00
|
|
|
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
|
|
|
srcrect := image.Rect(x, y, x+w, y+h)
|
2023-07-22 18:51:58 +00:00
|
|
|
draw.Copy(dst, image.Point{}, src, srcrect, draw.Over, nil)
|
|
|
|
return dst, nil
|
2022-08-12 06:03:06 +00:00
|
|
|
}
|
|
|
|
|
2022-08-13 06:11:36 +00:00
|
|
|
// ReCrop an image, loading the original image from disk. Returns the newly created filename.
|
|
|
|
func ReCrop(filename string, x, y, w, h int) (string, error) {
|
|
|
|
var (
|
|
|
|
ext = filepath.Ext(filename)
|
|
|
|
cropFilename = NewFilename(ext)
|
|
|
|
)
|
|
|
|
|
|
|
|
fh, err := os.Open(DiskPath(filename))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode the image.
|
|
|
|
var img image.Image
|
|
|
|
switch ext {
|
2023-07-22 18:51:58 +00:00
|
|
|
case ".jpg", ".jpeg", ".jpe":
|
|
|
|
// NOTE: new uploads enforce .jpg extension, some legacy pics may have slipped thru
|
2022-08-13 06:11:36 +00:00
|
|
|
img, err = jpeg.Decode(fh)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
case ".png":
|
|
|
|
img, err = png.Decode(fh)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return "", errors.New("unsupported file type")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Crop it.
|
2023-07-22 18:51:58 +00:00
|
|
|
croppedImg, err := Crop(img, x, y, w, h)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2022-08-13 06:11:36 +00:00
|
|
|
|
|
|
|
// Write it.
|
2023-06-26 05:55:07 +00:00
|
|
|
err = ToDisk(cropFilename, ext, croppedImg, nil)
|
2022-08-13 06:11:36 +00:00
|
|
|
return cropFilename, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseCropCoords splits a string of x,y,w,h values into proper crop coordinates, or nil.
|
|
|
|
func ParseCropCoords(coords string) []int {
|
|
|
|
// Parse and validate crop coordinates.
|
|
|
|
var crop []int
|
|
|
|
if len(coords) > 0 {
|
|
|
|
aints := strings.Split(coords, ",")
|
|
|
|
if len(aints) >= 4 {
|
|
|
|
crop = []int{}
|
|
|
|
for i, aint := range aints {
|
|
|
|
if number, err := strconv.Atoi(strings.TrimSpace(aint)); err == nil {
|
|
|
|
crop = append(crop, number)
|
|
|
|
} else {
|
|
|
|
log.Error("Failure to parse crop coordinates ('%s') at number %d: %s", coords, i, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-07-22 18:51:58 +00:00
|
|
|
|
2022-08-13 06:11:36 +00:00
|
|
|
return crop
|
|
|
|
}
|
|
|
|
|
2022-08-12 06:03:06 +00:00
|
|
|
// ToDisk commits a photo image to disk in the right file format.
|
|
|
|
//
|
|
|
|
// Filename is like NewFilename() and it goes to e.g. "./web/static/photos/"
|
2023-06-26 05:55:07 +00:00
|
|
|
//
|
|
|
|
// Encoding rules:
|
|
|
|
// - JPEG and PNG uploads are saved as JPEG
|
|
|
|
// - GIF uploads are transmuted to MP4
|
|
|
|
func ToDisk(filename string, extension string, img image.Image, cfg *UploadConfig) error {
|
|
|
|
// GIF path handled specially (note: it will come in with extension=".mp4")
|
|
|
|
if extension == ".gif" || extension == ".mp4" {
|
|
|
|
// Requires an upload config (ReCrop not supported)
|
|
|
|
if cfg == nil {
|
|
|
|
return errors.New("can't update your GIF after original upload")
|
|
|
|
}
|
|
|
|
return GifToMP4(filename, cfg)
|
|
|
|
}
|
|
|
|
|
2022-08-12 06:03:06 +00:00
|
|
|
if path, err := EnsurePath(filename); err == nil {
|
|
|
|
fh, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer fh.Close()
|
|
|
|
|
|
|
|
switch extension {
|
2023-07-22 18:51:58 +00:00
|
|
|
case ".jpg", ".jpe", ".jpeg", ".png":
|
|
|
|
// NOTE: new uploads enforce .jpg extension always, some legacy pics (.png too) may have slipped thru
|
2022-08-12 06:03:06 +00:00
|
|
|
jpeg.Encode(fh, img, &jpeg.Options{
|
|
|
|
Quality: config.JpegQuality,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("couldn't EnsurePath: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2022-08-13 06:11:36 +00:00
|
|
|
|
|
|
|
// Delete a photo from disk.
|
|
|
|
func Delete(filename string) error {
|
2022-08-14 21:40:57 +00:00
|
|
|
if len(filename) > 0 {
|
|
|
|
return os.Remove(DiskPath(filename))
|
|
|
|
}
|
|
|
|
return errors.New("filename is required")
|
2022-08-13 06:11:36 +00:00
|
|
|
}
|