Merge pull request #5 from brittonhayes/bhayes/tobytes
feat: ToBytes() Method
This commit is contained in:
commit
d27652b576
2 changed files with 73 additions and 1 deletions
60
example/example_http.go
Normal file
60
example/example_http.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jdxyw/generativeart"
|
||||
"github.com/jdxyw/generativeart/arts"
|
||||
"github.com/jdxyw/generativeart/common"
|
||||
)
|
||||
|
||||
func main() {
|
||||
address := ":8090"
|
||||
log.Println("Server started at", address)
|
||||
|
||||
// Initialize handlers
|
||||
http.HandleFunc("/", drawHandler)
|
||||
log.Fatal(http.ListenAndServe(address, nil))
|
||||
}
|
||||
|
||||
// drawHandler is writes a piece of generative art
|
||||
// as a response to an http request
|
||||
func drawHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// Log Requests
|
||||
log.Printf("method=%s path=%s ", r.Method, r.RequestURI)
|
||||
|
||||
// Draw the image to bytes
|
||||
b, err := drawMyBytes()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Set content headers
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
|
||||
|
||||
// Write image to response
|
||||
if _, err = w.Write(b); err != nil {
|
||||
log.Fatal("unable to write image.")
|
||||
}
|
||||
}
|
||||
|
||||
func drawMyBytes() ([]byte, error) {
|
||||
|
||||
// Generate a new image
|
||||
rand.Seed(time.Now().Unix())
|
||||
c := generativeart.NewCanva(500, 500)
|
||||
c.SetBackground(common.Black)
|
||||
c.FillBackground()
|
||||
c.SetColorSchema(common.DarkRed)
|
||||
c.SetForeground(common.LightPink)
|
||||
c.Draw(arts.NewJanus(10, 0.2))
|
||||
|
||||
// Return the image as []byte
|
||||
return c.ToBytes()
|
||||
}
|
|
@ -1,13 +1,15 @@
|
|||
package generativeart
|
||||
|
||||
import (
|
||||
"github.com/jdxyw/generativeart/common"
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
|
||||
"github.com/jdxyw/generativeart/common"
|
||||
)
|
||||
|
||||
type Engine interface {
|
||||
|
@ -169,3 +171,13 @@ func (c *Canva) ToJPEG(path string) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ToBytes returns the image as a jpeg-encoded []byte
|
||||
func (c *Canva) ToBytes() ([]byte, error) {
|
||||
buffer := new(bytes.Buffer)
|
||||
if err := jpeg.Encode(buffer, c.Img(), nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue