To create thumbnails and smaller versions of images in Go, you can use the github.com/nfnt/resize
package. This package provides an easy way to resize images while maintaining their aspect ratio.
Here's an example code that demonstrates how to create thumbnails and smaller versions of images using this package:
package main
import (
"fmt"
"image"
"image/jpeg"
"log"
"os"
"github.com/nfnt/resize"
)
func main() {
// Open the image file
file, err := os.Open("input.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Decode the image
img, _, err := image.Decode(file)
if err != nil {
log.Fatal(err)
}
// Create a thumbnail with a maximum width of 100 pixels
thumbnail := resize.Thumbnail(100, 100, img, resize.Lanczos3)
// Save the thumbnail to a file
outputFile, err := os.Create("thumbnail.jpg")
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
jpeg.Encode(outputFile, thumbnail, nil)
fmt.Println("Thumbnail created!")
// Create a smaller version of the image with a width of 500 pixels
small := resize.Resize(500, 0, img, resize.Lanczos3)
// Save the smaller version to a file
outputFile, err = os.Create("small.jpg")
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
jpeg.Encode(outputFile, small, nil)
fmt.Println("Smaller version created!")
}
In this example, we first open the image file using os.Open
and decode it using the image.Decode
function. Then, we create a thumbnail of the image using resize.Thumbnail
by specifying a maximum width and height for the thumbnail. We also specify the resizing algorithm to be used (in this case, resize.Lanczos3
).
Next, we save the thumbnail to a file using jpeg.Encode
. The same process is repeated to create a smaller version of the image, with a specific width, using resize.Resize
.
Make sure to replace "input.jpg"
with the path to your input image file. The thumbnails and smaller versions of the images will be saved as "thumbnail.jpg"
and "small.jpg"
respectively.