Skip to content

Instantly share code, notes, and snippets.

@antonfisher
Last active April 18, 2024 06:47
Show Gist options
  • Save antonfisher/9ad6b6535c1f5e9188b8536b9205284e to your computer and use it in GitHub Desktop.
Save antonfisher/9ad6b6535c1f5e9188b8536b9205284e to your computer and use it in GitHub Desktop.
Utility to add transparent horizontal stripes to an image.
//
// Add transparent horizontal stripes to an image.
//
// Usage:
// go run stripes.go image.png 6 12 420
// | | | |
// | | | `- top and bottom padding
// | | `---- space between stripes
// | `------ stripes width
// `---------------- original file name or path
// Output:
// image-stripes.png
//
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
"path/filepath"
"strconv"
"strings"
)
func main() {
// Parse arguments.
if len(os.Args) < 5 {
fmt.Printf("Wrong number of arguments.\nUsage:\n\tgo run stripes.go 10 5 100 image.png\n")
return
}
inputFileName := os.Args[1]
fmt.Printf("Image name: %s\n", inputFileName)
stripeWidth, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Printf("Cannot parse second argument (stripe width, int): %s\n", err)
return
}
fmt.Printf("Stripes width: %d\n", stripeWidth)
stripeSpacing, err := strconv.Atoi(os.Args[3])
if err != nil {
fmt.Printf("Cannot parse third argument (stripe spacing, int): %s\n", err)
return
}
fmt.Printf("Stripes spacing: %d\n", stripeSpacing)
padding, err := strconv.Atoi(os.Args[4])
if err != nil {
fmt.Printf("Cannot parse forth argument (padding, int): %s\n", err)
return
}
fmt.Printf("Padding: %d\n", padding)
// Open and decode the original image.
file, err := os.Open(inputFileName)
if err != nil {
fmt.Printf("Cannot open file: %s\n", err)
return
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
fmt.Printf("Cannot decode image: %s\n", err)
return
}
// Create and draw on a new image.
bounds := img.Bounds()
newImg := image.NewRGBA(bounds)
draw.Draw(newImg, bounds, img, bounds.Min, draw.Src)
transparent := color.RGBA{0, 0, 0, 0}
var y int = padding
for y < bounds.Max.Y-stripeSpacing-stripeWidth-padding {
rect := image.Rect(bounds.Min.X, y, bounds.Max.X, y+stripeWidth)
draw.Draw(newImg, rect, &image.Uniform{transparent}, image.Point{}, draw.Src)
y += stripeSpacing + stripeWidth
}
// Save the new image.
inputFileExt := filepath.Ext(inputFileName)
outputFileName := fmt.Sprintf(
"%s-stripes%s",
strings.TrimSuffix(filepath.Base(inputFileName), inputFileExt),
filepath.Ext(inputFileExt),
)
outputFile, err := os.Create(outputFileName)
if err != nil {
fmt.Printf("Cannot create file: %s\n", err)
return
}
defer outputFile.Close()
err = png.Encode(outputFile, newImg)
if err != nil {
fmt.Printf("Cannot encode file: %s\n", err)
return
}
fmt.Printf("File created: %s\n", outputFileName)
fmt.Printf("Done.\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment