2022-04-01 21:14:22 +02:00
|
|
|
package thumb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"image"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/disintegration/imaging"
|
|
|
|
"github.com/mandykoh/prism/meta/autometa"
|
|
|
|
|
2022-04-15 09:42:07 +02:00
|
|
|
"github.com/photoprism/photoprism/pkg/clean"
|
2022-04-01 21:14:22 +02:00
|
|
|
"github.com/photoprism/photoprism/pkg/colors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// OpenJpeg loads a JPEG image from disk, rotates it, and converts the color profile if necessary.
|
|
|
|
func OpenJpeg(fileName string, orientation int) (result image.Image, err error) {
|
|
|
|
if fileName == "" {
|
|
|
|
return result, fmt.Errorf("filename missing")
|
|
|
|
}
|
|
|
|
|
2022-04-15 09:42:07 +02:00
|
|
|
logName := clean.Log(filepath.Base(fileName))
|
2022-04-01 21:14:22 +02:00
|
|
|
|
|
|
|
// Open file.
|
|
|
|
fileReader, err := os.Open(fileName)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return result, err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer fileReader.Close()
|
|
|
|
|
2022-06-25 02:16:42 +02:00
|
|
|
// Reset file offset.
|
|
|
|
// see https://github.com/golang/go/issues/45902#issuecomment-1007953723
|
|
|
|
_, err = fileReader.Seek(0, 0)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return result, fmt.Errorf("%s on seek", err)
|
|
|
|
}
|
|
|
|
|
2022-04-01 21:14:22 +02:00
|
|
|
// Read color metadata.
|
|
|
|
md, imgStream, err := autometa.Load(fileReader)
|
|
|
|
|
2022-06-25 02:16:42 +02:00
|
|
|
// Decode image.
|
2022-04-01 21:14:22 +02:00
|
|
|
var img image.Image
|
|
|
|
|
|
|
|
if err != nil {
|
2022-07-06 23:01:54 +02:00
|
|
|
log.Warnf("thumb: %s in %s (read color metadata)", err, logName)
|
2022-04-01 21:14:22 +02:00
|
|
|
img, err = imaging.Decode(fileReader)
|
|
|
|
} else {
|
|
|
|
img, err = imaging.Decode(imgStream)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2022-06-25 02:16:42 +02:00
|
|
|
return result, fmt.Errorf("%s while decoding", err)
|
2022-04-01 21:14:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Read ICC profile and convert colors if possible.
|
|
|
|
if md != nil {
|
|
|
|
if iccProfile, err := md.ICCProfile(); err != nil || iccProfile == nil {
|
|
|
|
// Do nothing.
|
2022-07-06 23:01:54 +02:00
|
|
|
log.Tracef("thumb: %s has no color profile", logName)
|
2022-04-01 21:14:22 +02:00
|
|
|
} else if profile, err := iccProfile.Description(); err == nil && profile != "" {
|
2022-07-06 23:01:54 +02:00
|
|
|
log.Tracef("thumb: %s has color profile %s", logName, clean.Log(profile))
|
2022-04-01 21:14:22 +02:00
|
|
|
switch {
|
|
|
|
case colors.ProfileDisplayP3.Equal(profile):
|
|
|
|
img = colors.ToSRGB(img, colors.ProfileDisplayP3)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-06 23:01:54 +02:00
|
|
|
// Adjust orientation.
|
2022-04-01 21:14:22 +02:00
|
|
|
if orientation > 1 {
|
|
|
|
img = Rotate(img, orientation)
|
|
|
|
}
|
|
|
|
|
|
|
|
return img, nil
|
|
|
|
}
|