beta.blog

Golang: Convert .webm to .jpg / .png

by on Nov.01, 2024, under News

Many of the search results in image searches nowadays spit out images in .webp format. According to Google for Developers, this is the definition:

WebP is a modern image format that provides superior lossless and lossy compression for images on the web. Using WebP, webmasters and web developers can create smaller, richer images that make the web faster. WebP lossless images are 26% smaller in size compared to PNGs.

Although these are displayed correctly in the web browser, they cannot be opened by many other programs. Because of this, here is a small Go program that reads a webp format and converts it to .jpg or .png.

package main

import (
	"image"
	"image/jpeg"
	"image/png"
	"os"
	"path/filepath"
	"fmt"
	_ "golang.org/x/image/webp"
)

func main() {
	if len(os.Args) != 3 {
		fmt.Println("Usage: go run main.go input.webp output.[png|jpg]")
		return
	}

	inputPath := os.Args[1]
	outputPath := os.Args[2]
	outputExt := filepath.Ext(outputPath)

	webpFile, err := os.Open(inputPath)
	if err != nil {
		fmt.Printf("Error opening input file: %v\n", err)
		return
	}
	defer webpFile.Close()

	img, _, err := image.Decode(webpFile)
	if err != nil {
		fmt.Printf("Error decoding WebP file: %v\n", err)
		return
	}

	outputFile, err := os.Create(outputPath)
	if err != nil {
		fmt.Printf("Error creating output file: %v\n", err)
		return
	}
	defer outputFile.Close()

	switch outputExt {
	case ".png":
		err = png.Encode(outputFile, img)
		if err != nil {
			fmt.Printf("Error encoding PNG file: %v\n", err)
		}
	case ".jpg", ".jpeg":
		err = jpeg.Encode(outputFile, img, nil)
		if err != nil {
			fmt.Printf("Error encoding JPEG file: %v\n", err)
		}
	default:
		fmt.Println("Unsupported output format. Please use .png or .jpg/.jpeg")
		return
	}

	fmt.Println("Conversion successful!")
}

To compile simply do:

go get
go build

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!