Skip to content

Instantly share code, notes, and snippets.

@ilfey
Created June 22, 2023 16:10
Show Gist options
  • Select an option

  • Save ilfey/cf4b75081359ab19f144584db479198f to your computer and use it in GitHub Desktop.

Select an option

Save ilfey/cf4b75081359ab19f144584db479198f to your computer and use it in GitHub Desktop.
script for create demotivator image on golang
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
"log"
"os"
)
func OpenImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
im, err := png.Decode(file)
if err != nil {
return nil, err
}
return im, nil
}
func CreateDemotivator(im image.Image, p int) *image.RGBA {
dem := image.NewRGBA(image.Rect(0, 0, 512, 512))
imX := int(dem.Bounds().Max.X/2 - 256/2)
imY := int(float32(dem.Bounds().Max.Y)/2.5 - 256/2)
// set background and block
for y := dem.Bounds().Min.Y; y < dem.Bounds().Max.Y; y++ {
for x := dem.Bounds().Min.X; x < dem.Bounds().Max.X; x++ {
if ((y == imY-p || y == imY+256+p) && (x > imX-p) && !(x > imX+256+p)) || ((x == imX-p || x == imX+256+p) && (y > imY-p) && !(y > imY+256+p)) {
dem.Set(x, y, color.White)
} else {
dem.Set(x, y, color.Black)
}
}
}
return dem
}
func SetImage(im image.Image, dem *image.RGBA) {
imagePos := image.Rect(
int(dem.Bounds().Max.X/2-im.Bounds().Max.X/2),
int(float32(dem.Bounds().Max.Y)/2.5-float32(im.Bounds().Max.X/2)),
int(dem.Bounds().Max.X/2-im.Bounds().Max.X/2)+im.Bounds().Max.X,
int(float32(dem.Bounds().Max.Y)/2.5-float32(im.Bounds().Max.X/2))+im.Bounds().Max.Y,
)
draw.Draw(dem, imagePos, im, image.Point{0, 0}, draw.Src)
}
func SetText(dem *image.RGBA, title string) {
col := color.White
point := fixed.Point26_6{fixed.I(10), fixed.I(100)}
d := &font.Drawer{
Dst: dem,
Src: image.NewUniform(col),
Face: basicfont.Face7x13,
Dot: point,
}
d.DrawString(title)
}
func main() {
image, err := OpenImage("example.png")
if err != nil {
log.Fatal(err)
}
dem := CreateDemotivator(image, 10)
SetImage(image, dem)
SetText(dem, "cock fruto nya")
// save png
file, err := os.Create("output.png")
if err != nil {
log.Fatal(err)
}
defer file.Close()
png.Encode(file, dem)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment