To convert between different image formats in Go, you can utilize the image
and image/png
packages from the standard library. Here's an example code that demonstrates how to convert a JPEG image to PNG using Go:
package main
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
)
func main() {
// Open the JPEG file
jpegFile, err := os.Open("input.jpg")
if err != nil {
fmt.Println("Failed to open JPEG:", err)
return
}
defer jpegFile.Close()
// Decode the JPEG image
jpegImg, err := jpeg.Decode(jpegFile)
if err != nil {
fmt.Println("Failed to decode JPEG:", err)
return
}
// Create a new PNG file
pngFile, err := os.Create("output.png")
if err != nil {
fmt.Println("Failed to create PNG:", err)
return
}
defer pngFile.Close()
// Encode the image as PNG
err = png.Encode(pngFile, jpegImg)
if err != nil {
fmt.Println("Failed to encode PNG:", err)
return
}
fmt.Println("Conversion successful!")
}
Make sure to replace "input.jpg"
with the path to your JPEG file, and "output.png"
with the desired output PNG file path. This code reads the JPEG image, decodes it, and then saves it as a PNG image.
To convert between other image formats, you can use similar approaches but with the appropriate image and encoding packages provided by the Go standard library.