How to Work with PNG, JPEG, and GIF in Go

Use the `image`, `image/png`, `image/jpeg`, and `image/gif` packages in the standard library to decode and encode these formats. The `image.Decode` function automatically detects the format from the file content, while `image/png.Encode`, `image/jpeg.Encode`, and `image/gif.Encode` handle saving.

How to Work with PNG, JPEG, and GIF in Go

Use the image, image/png, image/jpeg, and image/gif packages in the standard library to decode and encode these formats. The image.Decode function automatically detects the format from the file content, while image/png.Encode, image/jpeg.Encode, and image/gif.Encode handle saving.

package main

import (
	"image"
	"image/jpeg"
	"image/png"
	"os"
)

func main() {
	// Decode any format (PNG, JPEG, GIF)
	f, err := os.Open("input.jpg")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	img, _, err := image.Decode(f)
	if err != nil {
		panic(err)
	}

	// Encode to PNG
	pngFile, err := os.Create("output.png")
	if err != nil {
		panic(err)
	}
	defer pngFile.Close()

	if err := png.Encode(pngFile, img); err != nil {
		panic(err)
	}

	// Encode to JPEG
	// JPEG does not support transparency, so we convert to RGBA if necessary
	jpegFile, err := os.Create("output.jpg")
	if err != nil {
		panic(err)
	}
	defer jpegFile.Close()

	// Ensure the image is in a format JPEG supports (RGBA)
	if _, ok := img.(*image.RGBA); !ok {
		bounds := img.Bounds()
		newImg := &image.RGBA{
			Pix:    make([]byte, bounds.Dx()*bounds.Dy()*4),
			Stride: bounds.Dx() * 4,
			Rect:   bounds,
		}
		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
			for x := bounds.Min.X; x < bounds.Max.X; x++ {
				r, g, b, a := img.At(x, y).RGBA()
				idx := (y-bounds.Min.Y)*newImg.Stride + (x-bounds.Min.X)*4
				newImg.Pix[idx] = uint8(r >> 8)
				newImg.Pix[idx+1] = uint8(g >> 8)
				newImg.Pix[idx+2] = uint8(b >> 8)
				newImg.Pix[idx+3] = uint8(a >> 8)
			}
		}
		img = newImg
	}

	if err := jpeg.Encode(jpegFile, img, nil); err != nil {
		panic(err)
	}

	// Encode to GIF (requires image/gif import)
	// gifFile, _ := os.Create("output.gif")
	// gif.Encode(gifFile, img, nil)
}