/bs/image.go
package bs
import (
"image"
"image/draw"
"log"
"os"
"bytex64.net/code/bitsmash/palette"
)
func loadImage(filename string, opts *EncodeOpts) image.PalettedImage {
reader, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer reader.Close()
img, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
size := img.Bounds().Size()
if size.X > 128 {
log.Fatal("Image width must be less than 128 pixels")
}
// Pad the width to one of our valid sizes
if !validSize(size.X) {
var newWidth int
for _, s := range(sizes) {
if size.X < s {
newWidth = s
break
}
}
log.Printf("Padding image width %d to %d pixels", size.X, newWidth)
r := image.Rect(0, 0, newWidth, size.Y)
newImage := image.NewRGBA(r)
draw.Draw(newImage, r, image.Transparent, image.ZP, draw.Src)
draw.Draw(newImage, img.Bounds(), img, image.ZP, draw.Src)
img = newImage
}
// If no palette has been specified, automatically select one
if (opts.Palette == -1) {
opts.Palette = findPalette(img)
log.Printf("Automatically selected palette %d\n", opts.Palette)
}
// Convert to the selected palette
pImage := image.NewPaletted(img.Bounds(), palette.Palettes[opts.Palette])
draw.Draw(pImage, img.Bounds(), img, image.ZP, draw.Src)
return pImage
}
func getPixelList(img image.PalettedImage) []uint8 {
p := img.(*image.Paletted)
return p.Pix
}
func (self *BitSmash) toImage() image.PalettedImage {
self.unpackRepeat()
size := self.Size()
img := image.NewPaletted(image.Rectangle{image.Pt(0, 0), size}, palette.Palettes[self.palette])
c := 0
for _, p := range(self.packetList) {
pixels := p.Pixels()
copy(img.Pix[c:], pixels)
c += len(pixels)
}
return img
}