77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"image"
|
|
"image/jpeg"
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
|
|
"github.com/nfnt/resize"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// resizeCmd represents the resize command
|
|
var resizeCmd = &cobra.Command{
|
|
Use: "resize [input_file] [output_file] [width]",
|
|
Short: "Resize an image to the specified width",
|
|
Long: `Resize an image to the specified width using Lanczos3 interpolation.
|
|
Example: dttt resize input.jpg output.jpg 300`,
|
|
Args: cobra.ExactArgs(3),
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
if len(args) == 0 {
|
|
cmd.Help()
|
|
return
|
|
}
|
|
|
|
inputFile := args[0]
|
|
outputFile := args[1]
|
|
widthStr := args[2]
|
|
|
|
width, err := strconv.Atoi(widthStr)
|
|
if err != nil {
|
|
log.Fatal("Invalid width:", err)
|
|
}
|
|
|
|
resizeImage(inputFile, outputFile, width)
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(resizeCmd)
|
|
}
|
|
|
|
func resizeImage(inputFile, outputFile string, width int) {
|
|
// Open the input image file
|
|
input, err := os.Open(inputFile)
|
|
if err != nil {
|
|
log.Fatal("Error opening input file:", err)
|
|
}
|
|
defer input.Close()
|
|
|
|
// Decode the input image file
|
|
img, _, err := image.Decode(input)
|
|
if err != nil {
|
|
log.Fatal("Error decoding input image:", err)
|
|
}
|
|
|
|
// Resize the image to the target width
|
|
resizedImg := resize.Resize(uint(width), 0, img, resize.Lanczos3)
|
|
|
|
// Create the output image file
|
|
output, err := os.Create(outputFile)
|
|
if err != nil {
|
|
log.Fatal("Error creating output file:", err)
|
|
}
|
|
defer output.Close()
|
|
|
|
// Write the resized image to the output file
|
|
if err := jpeg.Encode(output, resizedImg, nil); err != nil {
|
|
log.Fatal("Error encoding resized image:", err)
|
|
}
|
|
|
|
fmt.Println("Image resized successfully!")
|
|
}
|
|
|