diff --git a/example/example_http.go b/example/example_http.go new file mode 100644 index 0000000..4c5c361 --- /dev/null +++ b/example/example_http.go @@ -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() +} diff --git a/generativeart.go b/generativeart.go index 207b6e3..9fc30a8 100644 --- a/generativeart.go +++ b/generativeart.go @@ -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 +}