use a library for better image orientation handling

This commit is contained in:
2023-12-23 01:20:20 -07:00
parent f0292c325e
commit 9be49cb871
3 changed files with 12 additions and 64 deletions

View File

@ -9,7 +9,6 @@ import (
"image"
"image/jpeg"
"image/png"
"io"
"mime"
"mime/multipart"
@ -20,7 +19,7 @@ import (
"strings"
"time"
"github.com/nfnt/resize"
"github.com/disintegration/imaging"
"github.com/urfave/cli/v2"
)
@ -149,28 +148,10 @@ func cleanUpTempFile(fileLocation string) error {
func resizeImage(fileLocation string, format string) (string, error) {
// load the image
file, err := os.Open(fileLocation)
if err != nil {
return "", fmt.Errorf("error opening file | %w", err)
}
defer file.Close()
var img image.Image
fileMimeType := mime.TypeByExtension(path.Ext(fileLocation))
if fileMimeType == "image/jpeg" {
// decode the image
img, err = jpeg.Decode(file)
if err != nil {
return "", fmt.Errorf("error decoding jpeg image | %w", err)
}
} else if fileMimeType == "image/png" {
// decode the image
img, err = png.Decode(file)
if err != nil {
return "", fmt.Errorf("error decoding png image | %w", err)
}
} else {
return "", fmt.Errorf("unsupported file type | %v", fileMimeType)
img, err := imaging.Open(fileLocation, imaging.AutoOrientation(true))
if err != nil {
return "", fmt.Errorf("error opening image | %w", err)
}
// check if the image is already the correct size
@ -202,47 +183,7 @@ func resizeImage(fileLocation string, format string) (string, error) {
y1 = 768
}
inFormat := "wide"
if width < height {
inFormat = "tall"
}
if width == height {
inFormat = "square"
}
// if not, resize the image
// scale the original image to the new size
var resizedImage image.Image
if format == "wide" {
resizedImage = resize.Resize(uint(x1), 0, img, resize.Lanczos3)
}
if format == "tall" {
resizedImage = resize.Resize(0, uint(y1), img, resize.Lanczos3)
}
if format == "square" {
if inFormat == "wide" {
resizedImage = resize.Resize(0, uint(y1), img, resize.Lanczos3)
}
if inFormat == "tall" {
resizedImage = resize.Resize(uint(x1), 0, img, resize.Lanczos3)
}
if inFormat == "square" {
resizedImage = resize.Resize(uint(x1), uint(y1), img, resize.Lanczos3)
}
}
// crop the image to the final correct size
// start by getting the center of the image
tempBounds := resizedImage.Bounds()
x0 := tempBounds.Max.X/2 - x1/2
y0 := tempBounds.Max.Y/2 - y1/2
xMax := x0 + x1
yMax := y0 + y1
croppedImageRect := image.Rect(x0, y0, xMax, yMax)
rgba := convertToRGBA(resizedImage)
croppedImage := rgba.SubImage(croppedImageRect)
croppedImage := imaging.Fill(img, x1, y1, imaging.Center, imaging.Lanczos)
// save the image to a temp file
tempFile, err := os.CreateTemp("", "i2v*"+path.Ext(fileLocation))