bedrocktool/utils/images.go

61 lines
1.5 KiB
Go
Raw Permalink Normal View History

2022-09-04 14:26:32 +00:00
package utils
import (
"image"
"image/color"
2023-02-12 21:22:44 +00:00
"image/png"
"os"
2022-09-04 14:26:32 +00:00
"unsafe"
)
func Img2rgba(img *image.RGBA) []color.RGBA {
2023-04-10 17:55:08 +00:00
return unsafe.Slice((*color.RGBA)(unsafe.Pointer(unsafe.SliceData(img.Pix))), len(img.Pix)/4)
2022-09-04 14:26:32 +00:00
}
2023-02-12 21:22:44 +00:00
func loadPng(path string) (*image.RGBA, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
img, err := png.Decode(f)
if err != nil {
return nil, err
}
2023-04-12 12:10:45 +00:00
return (*image.RGBA)(img.(*image.NRGBA)), nil
2023-02-12 21:22:44 +00:00
}
2022-09-04 14:26:32 +00:00
// LERP is a linear interpolation function
func LERP(p1, p2, alpha float64) float64 {
return (1-alpha)*p1 + alpha*p2
}
func blendColorValue(c1, c2, a uint8) uint8 {
return uint8(LERP(float64(c1), float64(c2), float64(a)/float64(0xff)))
}
func blendAlphaValue(a1, a2 uint8) uint8 {
return uint8(LERP(float64(a1), float64(0xff), float64(a2)/float64(0xff)))
}
func BlendColors(c1, c2 color.RGBA) (ret color.RGBA) {
ret.R = blendColorValue(c1.R, c2.R, c2.A)
ret.G = blendColorValue(c1.G, c2.G, c2.A)
ret.B = blendColorValue(c1.B, c2.B, c2.A)
ret.A = blendAlphaValue(c1.A, c2.A)
return ret
}
2023-01-29 21:20:13 +00:00
// DrawImgScaledPos draws src onto dst at bottomLeft, scaled to size
func DrawImgScaledPos(dst *image.RGBA, src *image.RGBA, bottomLeft image.Point, sizeScaled int) {
sbx := src.Bounds().Dx()
2023-01-29 21:20:13 +00:00
ratio := int(float64(sbx) / float64(sizeScaled))
for xOut := bottomLeft.X; xOut < bottomLeft.X+sizeScaled; xOut++ {
for yOut := bottomLeft.Y; yOut < bottomLeft.Y+sizeScaled; yOut++ {
xIn := (xOut - bottomLeft.X) * ratio
yIn := (yOut - bottomLeft.Y) * ratio
2023-02-08 11:00:36 +00:00
dst.Set(xOut, yOut, src.At(xIn, yIn))
}
}
}