Skip to content

Instantly share code, notes, and snippets.

@slawekkolodziej
Last active December 16, 2015 15:19
Show Gist options
  • Save slawekkolodziej/5455553 to your computer and use it in GitHub Desktop.
Save slawekkolodziej/5455553 to your computer and use it in GitHub Desktop.
hackkrk 4/2013 image upload
package main
import (
"encoding/json"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"time"
)
const (
GET_COLOR_URL = "http://localhost:12345/get-color"
)
type Response struct {
Id int
Color []interface{}
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
file, err := os.Open("img.png")
if err != nil {
log.Fatal(err)
}
img, _, err := image.Decode(file)
file.Close()
for {
handle_request(img)
}
}
func handle_request(img image.Image) {
resp, err := http.Get(GET_COLOR_URL)
resp_body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Fatal(err)
}
// unmarshall response
var resp_json Response
err = json.Unmarshal(resp_body, &resp_json)
rgba := getColor(resp_json.Color)
// draw image
rect := image.Rect(0, 0, 64, 64)
dest := image.NewRGBA(rect)
draw.Draw(dest, dest.Bounds(), &image.Uniform{rgba}, image.ZP, draw.Src)
draw.Draw(dest, rect, img, rect.Min, draw.Over)
// out := &bytes.Buffer{}
filename := fmt.Sprintf("out/%d.png", time.Now().UTC().UnixNano())
out, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
err = png.Encode(out, dest)
if err == nil {
fmt.Printf("saved %s\n", filename)
}
}
func getColor(color_data []interface{}) color.RGBA {
var rgb [3]uint8
if len(color_data) > 3 {
log.Fatal("InvalidColor")
}
for i := 0; i < 3; i++ {
switch color_data[i].(type) {
default:
log.Fatal("InvalidColor")
case float64:
rgb[i] = uint8(color_data[i].(float64))
}
}
return color.RGBA{rgb[0], rgb[1], rgb[2], 255}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment