如何提高读取二维码信息成功率

工作原因需要将微信的二维码信息读取出来,但是在读取的过程中发现很多二维码信息无法成功读取成功,
下面是一个解析二维码的类。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class QrDecoder {

private $qrCode;

public function __construct(){}

/**
* @author: MaHui <397091486@qq.com> 2018/10/25 - 17:56
*
* @param string $qrCode
*
* @return QrDecoder
*/
public function setQrCode(string $qrCode = 'images/qrcode/wxQrcode/fx_1.jpeg'): QrDecoder
{
$this->qrCode = $qrCode;

return $this;
}

/**
* 获取二维码信息
*
* @author: MaHui <397091486@qq.com> 2018/10/24 - 14:48
*
* @param array $images
*
* @return String
*/
public function getQrCodeInfo(): String
{
$imageResource = imagecreatefromstring(file_get_contents($this->qrCode));
// $qrcode = new QrReader($this->imageToString($imageResource), QrReader::SOURCE_TYPE_BLOB);

$width = imagesx($imageResource);
$height = imagesy($imageResource);

for ($zoom = 100; $zoom >= 10; $zoom -= 5) {
$new_width = $width * $zoom / 100;
$new_height = $height * $zoom / 100;
echo $width . '------' . $new_height . "\n";

$zoomResource = imagecreate(800, 500);

imagecopyresampled(
$zoomResource,
$imageResource,
0,
0,
0,
0,
$new_width,
$new_height,
$width,
$height
);

// imagepng($zoomResource, $this->qrCode, 0, PNG_NO_FILTER);
// imagedestroy($zoomResource);

try {
// $qrcode = new QrReader($this->qrCode);
$qrcode = new QrReader($this->imageToString($zoomResource), QrReader::SOURCE_TYPE_BLOB);
$numText = $qrcode->text();
if ($numText) {
echo ' FIND ' . $numText . ', ';
break;
}
} catch (\InvalidArgumentException $e) {
$numText = null;
}

echo '{' . $zoom . ' | ' . $numText . ' }, ';
}
return $qrcode->text();
}

/**
* 图片转二进制
*
* @author: MaHui <397091486@qq.com> 2018/10/25 - 17:51
*
* @param $image
*
* @return string
*/
private function imageToString($image): string
{
ob_start();
imagepng($image);
$string = ob_get_clean();
return $string;
}

提高二维码解析成功率主要是使用的 getQrCodeInfo() 这个方法。而其中关键点是其中的 for 循环体内的imagecopyresampled()

官方解释:

imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。

In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

如果源和目标的宽度和高度不同,则会进行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝(如果 dst_image 和 src_image 相同的话)区域,但如果区域交迭的话则结果不可预知


对照官方文档和代码,就可以知道意思了。缩小图片,使二维码的像素点更清晰。

如果你使用上述二维码不生效,可以试着将 for 循环的步进改变一下,调试到你需要的。数值越小你得到的程序的效率降低。


Author: rexmolo
Link: http://rexmolo.github.io/2019/04/06/how-to-improve-sucess-of-decode-for-qrcode/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.