From 99cc16d0ac8b3c21184f17a4e4b43e90103f0a8e Mon Sep 17 00:00:00 2001 From: Drahoslav Date: Mon, 8 Jan 2018 00:25:25 +0100 Subject: [PATCH] Implement DrawImage in svg context --- draw2dsvg/converters.go | 12 ++++++++++++ draw2dsvg/gc.go | 18 +++++++++++++----- draw2dsvg/svg.go | 11 +++++++++++ 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/draw2dsvg/converters.go b/draw2dsvg/converters.go index 59d5064..70c6ace 100644 --- a/draw2dsvg/converters.go +++ b/draw2dsvg/converters.go @@ -4,9 +4,13 @@ package draw2dsvg import ( + "bytes" + "encoding/base64" "fmt" "github.com/llgcode/draw2d" + "image" "image/color" + "image/png" "math" "strings" ) @@ -110,3 +114,11 @@ func toSvgTransform(mat draw2d.Matrix) string { mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], ) } + +func imageToSvgHref(image image.Image) string { + out := "data:image/png;base64," + pngBuf := &bytes.Buffer{} + png.Encode(pngBuf, image) + out += base64.RawStdEncoding.EncodeToString(pngBuf.Bytes()) + return out +} diff --git a/draw2dsvg/gc.go b/draw2dsvg/gc.go index b4a6dca..50cc7bf 100644 --- a/draw2dsvg/gc.go +++ b/draw2dsvg/gc.go @@ -353,6 +353,19 @@ func (gc *GraphicContext) SetFontSize(fontSize float64) { gc.recalc() } +// DrawImage draws the raster image in the current canvas +func (gc *GraphicContext) DrawImage(image image.Image) { + bounds := image.Bounds() + + gc.newGroup(0).Image = &Image{ + Href: imageToSvgHref(image), + X: bounds.Min.X, + Y: bounds.Min.Y, + Width: bounds.Max.X - bounds.Min.X, + Height: bounds.Max.Y - bounds.Min.Y, + } +} + /////////////////////////////////////// // TODO implement following methods (or remove if not neccesary) @@ -362,11 +375,6 @@ func (gc *GraphicContext) GetFontName() string { return fmt.Sprintf("%s:%d:%d:%d", fontData.Name, fontData.Family, fontData.Style, gc.Current.FontSize) } -// DrawImage draws the raster image in the current canvas -func (gc *GraphicContext) DrawImage(image image.Image) { - // panic("not implemented") -} - // ClearRect fills the specified rectangle with a default transparent color func (gc *GraphicContext) ClearRect(x1, y1, x2, y2 int) { // panic("not implemented") diff --git a/draw2dsvg/svg.go b/draw2dsvg/svg.go index 819832e..f703052 100644 --- a/draw2dsvg/svg.go +++ b/draw2dsvg/svg.go @@ -42,6 +42,7 @@ type Group struct { Groups []*Group `xml:"g"` Paths []*Path `xml:"path"` Texts []*Text `xml:"text"` + Image *Image `xml:"image"` } type Path struct { @@ -58,6 +59,16 @@ type Text struct { Style string `xml:"style,attr,omitempty"` } +type Image struct { + Href string `xml:"href,attr"` + X int `xml:"x,attr,omitempty"` + Y int `xml:"y,attr,omitempty"` + Width int `xml:"width,attr"` + Height int `xml:"height,attr"` +} + +/* font related elements */ + type Font struct { Identity Face *Face `xml:"font-face"`