130 lines
2.5 KiB
Go
130 lines
2.5 KiB
Go
package meowlib
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"encoding/json"
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"log"
|
|
"math"
|
|
"os"
|
|
|
|
"github.com/makiuchi-d/gozxing"
|
|
"github.com/makiuchi-d/gozxing/qrcode"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
func ServerFromUrl(url string) *Server {
|
|
var s Server
|
|
s.Url = url
|
|
return &s
|
|
}
|
|
|
|
func (Contact *ContactCard) AddUrls(urls []string) {
|
|
for _, url := range urls {
|
|
Contact.PullServers = append(Contact.PullServers, ServerFromUrl(url))
|
|
}
|
|
}
|
|
|
|
func (contact *ContactCard) Serialize() ([]byte, error) {
|
|
out, err := proto.Marshal(contact)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (contact *ContactCard) Compress() ([]byte, error) {
|
|
out, err := contact.Serialize()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var b bytes.Buffer
|
|
gz := gzip.NewWriter(&b)
|
|
if _, err := gz.Write(out); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if err := gz.Close(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println(b.Bytes())
|
|
return b.Bytes(), nil
|
|
}
|
|
|
|
func (contact *ContactCard) WritePng(filename string) {
|
|
out, err := proto.Marshal(contact)
|
|
if err != nil {
|
|
println(err)
|
|
}
|
|
size := int(math.Sqrt(float64(len(out))/3)) + 1
|
|
println(size)
|
|
|
|
// Create a colored i mage of the given width and height.
|
|
img := image.NewNRGBA(image.Rect(0, 0, size, size))
|
|
|
|
for y := 0; y < size; y++ {
|
|
for x := 0; x < size*3; x = x + 3 {
|
|
p1 := uint8(out[x+y])
|
|
p2 := uint8(out[x+y+1])
|
|
p3 := uint8(out[x+y+2])
|
|
img.Set(x/3, y, color.NRGBA{
|
|
R: p1,
|
|
G: p2,
|
|
B: p3,
|
|
A: 255,
|
|
})
|
|
}
|
|
}
|
|
|
|
f, err := os.Create(filename)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if err := png.Encode(f, img); err != nil {
|
|
f.Close()
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if err := f.Close(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
}
|
|
|
|
func (Contact *ContactCard) WriteQr(filename string) {
|
|
jsonContact, _ := json.Marshal(Contact)
|
|
qwriter := qrcode.NewQRCodeWriter()
|
|
code, err := qwriter.Encode(string(jsonContact), gozxing.BarcodeFormat_QR_CODE, 512, 512, nil)
|
|
if err != nil {
|
|
println(err.Error())
|
|
}
|
|
file, _ := os.Create("barcode.png")
|
|
defer file.Close()
|
|
|
|
// *BitMatrix implements the image.Image interface,
|
|
// so it is able to be passed to png.Encode directly.
|
|
_ = png.Encode(file, code)
|
|
|
|
}
|
|
|
|
func ReadQr(Filename string) ContactCard {
|
|
var contact ContactCard
|
|
// open and decode image file
|
|
file, _ := os.Open("qrcode.jpg")
|
|
img, _, _ := image.Decode(file)
|
|
|
|
// prepare BinaryBitmap
|
|
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
|
|
|
// decode image
|
|
qrReader := qrcode.NewQRCodeReader()
|
|
result, _ := qrReader.Decode(bmp, nil)
|
|
|
|
fmt.Println(result)
|
|
return contact
|
|
}
|