Giter VIP home page Giter VIP logo

go-qrcode's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-qrcode's Issues

UTF 8 support?

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/

Facing issue while generating qrcode png content

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?

Set DataMode manually

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.

Mistake in gf_poly_test.go?

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}}?

WriteColorFIle does not seem to work with RGBA values

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

use go mod

need tag for go mod use , i do not use go get

[FeatureRequest] Save QRCode to SVG, PDF or EPS as well as PNG

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来换行没用,请问是要用什么来进行换行呢,还是说这里不支持换行操作

Suboptimal segements chosen, causing bitmap generation to fail

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:

  • AlphaNumeric (single segment)
  • V4
  • Ecc H (Highest)
  • Changing 6998877 to 699E877 causes generation to succeed
func 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.

Memory Leak?

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
}

qrcode.Encode accept and []byte instead of string

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.

Go-LoggedAccountStats package missing request.

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

Pushing QR to client

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:

enter image description here

Any help?

it is difficult(not possible?) to scan qrcode with 2048bytes with fix png size 256(default setting)

  • The tested qrcode scanner is ios13.0 and iphone11. and the png is show on a web page.
  • it is difficult(not possible?) to scan qrcode with 2048bytes with fix png size 256(default setting). I never success scan once with this setting. scale up the web is not working either.

workaround1:

  • if the pixelsPerModule is in range 1.0 and 2.0 , make it to 1.0 and compute offset to make it in the center of the png.(do not try to large scale with nearest with 1.5x, it will make one Module more like two Modules from the scanner)
  • This workaround will make it can be scaned, but a little difficult(Like the iphone must face the computer screen parallel)

workaround2:

  • if the length of content is large than 512 , make the png size to at least 512x512.
  • This workaround will make it very easy to scan.
  • ps, scan a qrcode with 2048 bytes content is slow on ios13.0, The machine may have too much work to do.

incorrect range of timing patterns

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++ {.

go-qrcode/regular_symbol.go

Lines 172 to 181 in da1b656

func (m *regularSymbol) addTimingPatterns() {
value := true
for i := finderPatternSize + 1; i < m.size-finderPatternSize; i++ {
m.symbol.set(i, finderPatternSize-1, value)
m.symbol.set(finderPatternSize-1, i, value)
value = !value
}
}

No working with using dep modules

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

Add option to configure quiet zone

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

No Method of Altering Border

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.