meowlib/contactcard.go

100 lines
2.0 KiB
Go
Raw Normal View History

2022-09-06 09:30:45 +02:00
package meowlib
import (
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"log"
"math"
"os"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
)
func ServerFromUrl(url string) *Server {
var s Server
s.Url = url
return &s
}
2022-09-06 17:07:35 +02:00
func (Contact *ContactCard) AddUrls(urls []string) {
2022-09-06 09:30:45 +02:00
for _, url := range urls {
2022-09-06 17:07:35 +02:00
Contact.PullServers = append(Contact.PullServers, ServerFromUrl(url))
2022-09-06 09:30:45 +02:00
}
}
2022-09-06 17:07:35 +02:00
func (Contact *ContactCard) WritePng(filename string) {
jsonContact, _ := json.Marshal(Contact)
2022-09-06 09:30:45 +02:00
//imgdata := base64.StdEncoding.EncodeToString(jsonContact)
size := int(math.Sqrt(float64(len(jsonContact))/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(jsonContact[x+y])
p2 := uint8(jsonContact[x+y+1])
p3 := uint8(jsonContact[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)
}
}
2022-09-06 17:07:35 +02:00
func (Contact *ContactCard) WriteQr(FileName string) {
jsonContact, _ := json.Marshal(Contact)
2022-09-06 09:30:45 +02:00
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)
}
2022-09-06 17:07:35 +02:00
func ReadQr(FileName string) ContactCard {
var Contact ContactCard
2022-09-06 09:30:45 +02:00
// 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)
2022-09-06 17:07:35 +02:00
return Contact
2022-09-06 09:30:45 +02:00
}