-
-
Notifications
You must be signed in to change notification settings - Fork 111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The result is not the same as the original js lib #55
Comments
If I resize the image proportionally before crop it, the result is better but still not the same as the original one package main
import (
"fmt"
"image"
"image/jpeg"
"math"
"os"
"github.com/muesli/smartcrop"
"github.com/muesli/smartcrop/nfnt"
"github.com/nfnt/resize"
)
func main() {
f, _ := os.Open("/tmp/origin.jpeg")
img, _, _ := image.Decode(f)
img = resizeImage(img, 300, 300)
analyzer := smartcrop.NewAnalyzer(nfnt.NewDefaultResizer())
topCrop, _ := analyzer.FindBestCrop(img, 300, 300)
// The crop will have the requested aspect ratio, but you need to copy/scale it yourself
fmt.Printf("Top crop: %+v\n", topCrop)
type SubImager interface {
SubImage(r image.Rectangle) image.Image
}
croppedimg := img.(SubImager).SubImage(topCrop)
//save cropped image to file out.png
// Save cropped image to file
out, err := os.Create("/tmp/cropped.jpeg")
if err != nil {
fmt.Println("Failed to create the file:", err)
return
}
defer out.Close()
// Choose quality of the jpeg (1-100), higher is better quality
err = jpeg.Encode(out, croppedimg, &jpeg.Options{Quality: 90})
if err != nil {
fmt.Println("Failed to save the image:", err)
return
}
fmt.Println("Cropped image saved to /tmp/cropped.jpeg")
}
func resizeImage(img image.Image, targetWidth, targetHeight uint) image.Image {
// Calculate the scaling factor and dimensions for resizing
originalBounds := img.Bounds()
originalWidth := originalBounds.Dx()
originalHeight := originalBounds.Dy()
var scalingFactor float64
if originalWidth < originalHeight {
scalingFactor = float64(targetWidth) / float64(originalWidth)
} else {
scalingFactor = float64(targetHeight) / float64(originalHeight)
}
newWidth := uint(math.Round(float64(originalWidth) * scalingFactor))
newHeight := uint(math.Round(float64(originalHeight) * scalingFactor))
// Resize the image with the new dimensions
resizedImg := resize.Resize(newWidth, newHeight, img, resize.Lanczos3)
return resizedImg
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for maintaining this wonderful port from js lib
However I found the result sometimes is not the same as the original one. Not only the part of the image, but also the size of image is 512x512, even I use 300x300 in code.
oringal image



cropped use js version
cropped use this lib
The text was updated successfully, but these errors were encountered: