skip2 / go-qrcode Goto Github PK
View Code? Open in Web Editor NEW:sparkles: QR Code encoder (Go)
Home Page: http://go-qrcode.appspot.com
License: MIT License
:sparkles: QR Code encoder (Go)
Home Page: http://go-qrcode.appspot.com
License: MIT License
Please, encode this string
"one two три четыре fünf sechs"
and decode the resulting code. Last four words are decoded incorrectly.
The same thing happens if you encode this line in your example on your test site http://go-qrcode.appspot.com/
I am trying to use this library for generating QR code. I am calling qrcode.PNG() function to get bytes of qrcode in PNG form.
But the problem is, i am not getting consistent results from this lib.
Below is my code:
qcode, err := qrcode.New("CONTENT-TO-BE-USED", qrcode.Medium)
if err != nil {
fmt.Println(err)
}
b, err := qcode.PNG(100) // tried different sizes like 256, 140, 130, and 100
if err != nil {
fmt.Println(err)
}
t.QRCode = string(b)
here t.QRCode
is used in html template with image tag to load qr code on web page.
Anything is wrongly done here?
The classifyDataModes() method tries to detect which dataModeNumeric, dataModeAlphanumeric or dataModeByte to use. Interesting that there is also Japan mode which is not supported. Maybe it makes sense to support it?
I have to generate many qr codes as fast as possible so I want to set the mode manually to skip this detection.
Can we create a new field in the config to preset the mode?
The https://github.com/yeqown/go-qrcode allows to do that.
Hello,
Is there a reason that you NewWithForcedVersion is not exported?
It is very practical to be able to generate fix sizes.
Apologies in advance if I have misread your code. I was looking at test case #3 for TestGFPolyRemainder with
numerator = gfPoly{[]gfElement{1}},
denominator = gfPoly{[]gfElement{1, 0}}
remainder = gfPoly{[]gfElement{1}}
where coefficients are of the form a0 + a1 x + a2 x^2 + a3 x^3...
I read this test case as 1 mod (1 + 0 * x)
= 1 mod 1
= 0
!= 1
Did you mean to write remainder = gfPoly{[]gfElement{0}}
?
qrcode.WriteFile("http://www.aa.com?a=123", qrcode.Medium, 256, "qr.png")
用微信扫描生成的二维码,用浏览器打开,发现请求的网址变为https://www.aa.com/?a=123
问号前面多了一个斜杠,http变为https
I've been doing some tests with this library and it's been great so far, but for some reason whenever I try to generate a QR code with RGBA foreground/background colors the function will create a blank PNG whiteout outputting any errors.
For example:
fg := color.RGBA{0, 0, 0, 1} // black
bg := color.RGBA{0, 0, 0, 0} // white
qrcode.WriteColorFile("dummyData", qrcode.Medium, 300, bg, fg, "colored.png")
Will result in a blank 300x300 png
but doing this:
fg := color.CMYK{0, 0, 0, 100} // black
bg := color.CMYK{0, 0, 0, 0} // white
qrcode.WriteColorFile("dummyData", qrcode.Medium, 300, bg, fg, "colored.png")
Will correctly output a valid QR code and non-blank PNG, passing bg := color.White
and fg := color.Black
as stated in the documentation works too.
Am I doing something wrong with my RGBA values and this behavior is expected or an actual issue with RGBA implementation somewhere in the library?
Cheers
能否支持二维码下方添加文本,我在代码中没看到相关内容
Please update the demo site to the new go runtime so that the demo works
qrcode.WriteFile("123", qrcode.Highest, 100, "qr_highest.png")
Would this be possible?
能不能和其他图片一起合成一个带有图标的二维码?
need tag for go mod use , i do not use go get
Hi ! Thanks for this library. It would be nice to be able to save the QRCode to SVG, PDF or EPS as well as PNG.
For example, adding dependency to
https://github.com/tdewolff/canvas/
the qrcode.go could have
// Canvas returns the QR Code as an image.Image.
func (q *QRCode) Canvas() *canvas.Canvas {
// Based on Image...
}
and this can be saved to appropriate format using,
c := q.Canvas()
c.WriteFile("out.svg", svg.Writer)
c.WriteFile("out.pdf", pdf.Writer)
c.WriteFile("out.eps", eps.Writer)
c.WriteFile("out.png", rasterizer.PNGWriter(3.2))
Attached a draft modification.
Best,
E.
这个二维码的入参是一个string,我用换行符\n来换行没用,请问是要用什么来进行换行呢,还是说这里不支持换行操作
I use the library heavily to generate qr bitmaps (manually creating the image), so thank you for creating it!
The following test case should generate correctly:
6998877
to 699E877
causes generation to succeedfunc TestShouldCreateTheQrCode(t *testing.T) {
msg := "HTTPS://ABC.DE/F/393AABB6998877XYZ0518AUQCRVJN25"
// E <-- change to E and no crash
qrc, err := qrcode.NewWithForcedVersion(msg, 4, qrcode.Highest)
if err != nil {
t.Error(err)
}
qrc.Bitmap()
}
=== RUN TestShouldCreateTheQrCode
2020/06/17 12:26:01 BUG: got len 296, expected 288
--- FAIL: TestShouldCreateTheQrCode (0.00s)
panic: BUG: got len 296, expected 288 [recovered]
panic: BUG: got len 296, expected 288
I noticed that after the call to encoder.encode
the length is 290 (and somehow numPaddingBits() == -2?). In any case, I am not familiar enough with the code to debug fully yet, but will be giving it a try this afternoon.
The multi-segments by default kind of thing is clever, it just appears to be failing in this case. I feel that most users will calculate their version/recovery-level based on the published data lengths which assume single-segment, especially for high volumes.
stuck at go: finding github.com/skip2/go-qrcode latest
如何直接显示生成的图片,而不是保存成文件
png, err := qrcode.Encode("https://887d.com", qrcode.Medium, 256)
我想把png这个图片用golang直接显示出来,而不是保存成文件来显示,该如何做到,谢谢
I want to show the picture of PNG directly with golang instead of saving it as a file. Thank you.
Is there a memory leak problem with this library?
There is a web api with my application for generating QRCode.
I found that the memory footprint would be very high after many requests to this api and do not come down.
go version go1.11.2 windows/amd64
My Code like this:
func UserAuthQRCode(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Content-Type", "image/png")
authUrl := "..."
qrCodeImg, err := qrcode.Encode(
authUrl,
qrcode.Medium,
256)
if err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
_, _ = w.Write(qrCodeImg)
return
}
What is the maximum capacity for generating a QR code?
White margin is too big!
I hope to be a little smaller?!
When running:
qrcode "88c77c18" > code.png
The generated code seems to only decode to:
c77c18
How QRcode reduces or cancels blank margins
qrcode 如何减少空白边距或取消空白边距
Is there a plan to support versioning with Go modules?
Thank you.
PR
#29
hi mr, can we have this feature :D
Hi, we are using this library to encode output from json.Marshal
into a qrcode.
but converting []byte
to string
is a copy operation, and we want to minimize that.
having qrcode.Encode
variant that accept []byte
instead of string
would be great.
probably i'll be named qrcode.EncodeBytes
, with that we could reuse buffer and probably improve performance.
Hi. can I change the padding option before output will be generate to file image?
When calling the QRcode library, "go-qrcode", Go keeps referencing a "go-LoggedAccountStats", and asking for it to be installed. Is it possible to remove all references to "LoggedAccountStats" from go.qrcode?
WhipMeHarder
Trying to make login screen as WhatsApp, where the QR is pushed to the client for scanning, so I wrote the below server code:
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
_ "github.com/mattn/go-sqlite3"
"github.com/skip2/go-qrcode"
"google.golang.org/protobuf/proto"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types/events"
waLog "go.mau.fi/whatsmeow/util/log"
)
func eventHandler(evt interface{}) {
switch v := evt.(type) {
case *events.Message:
fmt.Println("Received a message!", v.Message.GetConversation())
}
}
func main() {
passer := &DataPasser{logs: make(chan string)}
http.HandleFunc("/", passer.handleHello)
go http.ListenAndServe(":9999", nil)
store.DeviceProps.Os = proto.String("WhatsApp GO")
dbLog := waLog.Stdout("Database", "DEBUG", true)
// Make sure you add appropriate DB connector imports, e.g. github.com/mattn/go-sqlite3 for SQLite
container, err := sqlstore.New("sqlite3", "file:datastore.db?_foreign_keys=on", dbLog)
if err != nil {
panic(err)
}
// If you want multiple sessions, remember their JIDs and use .GetDevice(jid) or .GetAllDevices() instead.
deviceStore, err := container.GetFirstDevice()
if err != nil {
panic(err)
}
clientLog := waLog.Stdout("Client", "DEBUG", true)
client := whatsmeow.NewClient(deviceStore, clientLog)
client.AddEventHandler(eventHandler)
if client.Store.ID == nil {
// No ID stored, new login
qrChan, _ := client.GetQRChannel(context.Background())
err = client.Connect()
if err != nil {
panic(err)
}
for evt := range qrChan {
switch evt.Event {
case "success":
{
passer.logs <- "success"
fmt.Println("Login event: success")
}
case "timeout":
{
passer.logs <- "timeout"
fmt.Println("Login event: timeout")
}
case "code":
{
passer.logs <- "new code"
fmt.Println("new code recieved")
img, err := qrcode.Encode(evt.Code, qrcode.Medium, 200) // evt.Code
if err != nil {
fmt.Println("error when write qrImage", err.Error())
}
passer.logs <- string(img)
}
}
}
} else {
// Already logged in, just connect
passer.logs <- "Already logged"
fmt.Println("Already logged")
err = client.Connect()
if err != nil {
panic(err)
}
}
// Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
client.Disconnect()
}
With the below api:
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"strconv"
"sync"
)
var (
mux sync.Mutex
)
type Result struct {
ResultType, Result string
}
type DataPasser struct {
logs chan string
}
func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {
setupCORS(&w, r)
w.Header().Set("Content-Type", "text/event-stream")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Internal error", 500)
return
}
flusher.Flush()
done := r.Context().Done()
defer fmt.Println("EXIT")
for {
select {
case <-done:
// the client disconnected
return
case m := <-p.logs:
fmt.Println(m)
if m == "new code" || m == "We are logging in" || m == "Already logged" || m == "timeout" || m == "success" {
if _, err := fmt.Fprintf(w, "data: %s\n\n", m); err != nil {
// Write to connection failed. Subsequent writes will probably fail.
return
}
flusher.Flush()
} else {
mux.Lock()
buffer := bytes.NewBuffer([]byte(m))
/* img, _, err := image.Decode(buffer)
if err != nil {
fmt.Println("err: ", err)
}
if err := jpeg.Encode(buffer, img, nil); err != nil {
log.Println("unable to encode image.")
} */
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Println("unable to write image.")
}
mux.Unlock()
flusher.Flush()
}
}
}
}
func setupCORS(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Cache-Control", "no-cache")
(*w).Header().Set("Connection", "keep-alive")
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
But stuck to read it in the client, I tried something as below, but got lost:
<html>
<head></head>
<body>
note: <span id="content"></span><br>
<img id="photo" style="display: block;-webkit-user-select: none;">
</body>
<script>
/* (function(){
document.getElementById("content").innerHTML='<object type="text/html" data="http://localhost:9999/" ></object>';
})();
*/
const myRequest = new Request('http://127.0.0.1:9999/', {
method: 'GET',
headers: new Headers(),
type: "arraybuffer",
mode: 'cors',
cache: 'default',
});
var source = new EventSource("http://127.0.0.1:9999/");
source.onmessage = function (event) {
console.log(event)
var counter = event.data; // JSON.parse(event.data);
document.getElementById("content").innerHTML = counter;
}
fetch(myRequest).then(response => {
console.log(response)
console.log(response.headers)
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(data => {
var obj = JSON.parse(str);
console.log(obj)
// Process your data as a JavaScript object
});
} if (contentType && contentType.indexOf("image/jpeg") !== -1) {
console.log("Image received")
return response.blob().then(data => {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var imageUrl = reader.result;
var img = document.querySelector("#photo");
img.src = imageUrl;
}
});
} else if (contentType && contentType.indexOf("text/event-stream") !== -1) {
return response.text().then(text => {
console.log(text)
var source = new EventSource("http://localhost:9999/");
source.onmessage = function (event) {
var response = event.data // JSON.parse(event.data);
document.getElementById("content").innerHTML = counter;
}
// Process your text as a String
});
} else if (contentType && contentType.indexOf("text/html") !== -1) {
return response.text().then(text => {
console.log(text)
var source = new EventSource("http://localhost:9999/");
source.onmessage = function (event) {
var response = event.data // JSON.parse(event.data);
document.getElementById("content").innerHTML = counter;
}
// Process your text as a String
});
}
});
</script>
</html>
If I run and see the displayed page, I see:
Any help?
Last iteration m.size-finderPatternSize-1
for adding timing pattern is on separator pattern.
It happens to be false
, but it seems to be a misunderstanding.
I think it should be for i := finderPatternSize + 1; i < m.size-finderPatternSize-1; i++ {
.
Lines 172 to 181 in da1b656
Can I just get the matrix? I want to print it to the console / 可以直接拿到矩阵吗,我想打印到控制台
thanks / 谢谢
Hi, are there examples of placing a logo in the centre of a qrcodeData, _ := qrcode.Encode(encodeme, 2, 256)
call?
dep ensure -add github.com/skip2/go-qrcode
Warning: Gopkg.lock is out of sync with Gopkg.toml or the project's imports.
Fetching sources...
ensure Solve(): No versions of github.com/skip2/go-qrcode met constraints:
master: unable to update checked out version: : command failed: [git checkout 7ac0b40]: exit status 1
add_special_string_tests: unable to update checked out version: : command failed: [git checkout 5064bf1]: exit status 1
fix_scaling: unable to update checked out version: : command failed: [git checkout cb3bf7b]: exit status 1
fix_unnormalised_remainder: unable to update checked out version: : command failed: [git checkout d47ab36]: exit status 1
wiki: unable to update checked out version: : command failed: [git checkout 2ce9a30]: exit status 1
There are use cases, where predefined quiet zone is not desired. Currently,
there no way to configure it, only change hardcoded value.
I can implement it myself and send pull request (sorry for github slang)), but
it would be great to hear your answer and opinion before.
And thanks for the amazing library. The best golang QR library I've tried so
far. Also code is super easy to read and understand (especially after reading
code of other QR-encoding libraries).
Original issue reported on code.google.com by [email protected]
on 24 Feb 2015 at 5:09
Is there no way to alter the border on this? I see there is a way to disable the border, but no way to define the border's value.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.