- Saved searches
- Use saved searches to filter your results more quickly
- License
- splitbrain/php-qrcode
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Saved searches
- Use saved searches to filter your results more quickly
- License
- lasalesi/phpqrcode
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Генерация QR-кода в PHP
- Быстрый старт
- Вывод в браузер:
- Сохранение в файл:
- Описание параметров
- Данные в QR-коде
- Набрать номер телефона:
- Написать SMS:
- Добавить контакт:
- Email:
- Мессенджеры:
- Прозрачный фон
- Изменить цвет фона
- Изменить цвет пикселей
- Инверсия цветов
- Логотип в центре
- Генерируем QR-код на PHP
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
barcode.php — Generate QR Code from a single PHP file. MIT license.
License
splitbrain/php-qrcode
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Generate SVG QR Codes. MIT license.
composer require splitbrain/php-qrcode
use splitbrain\phpQRCode\QRCode; echo QRCode::svg('hello world');
The above will directly output the generated SVG file. This file has no styles attached. Use CSS to style howver you want it:
s — Symbology (type of QR code). One of:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHP library to produce QR Codes
License
lasalesi/phpqrcode
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP library to produce QR Codes
This is PHP implementation of QR Code 2-D barcode generator. It is pure-php LGPL-licensed implementation based on C libqrencode by Kentaro Fukuchi.
It is tested to work with a standard Debian 9 (stretch), php7.0 and apache2.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License (LICENSE file) for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
If you want to recreate cache by yourself make sure cache directory is writable and you have permisions to write into it. Also make sure you are able to read files in it if you have cache option enabled
Feel free to modify config constants in qrconfig.php file. Read about it in provided comments and project wiki page (links in README file)
Refer to the /samples section to get a quick start
Hardcoded QR code with settings, output to browser
WARNING! it should be FIRST and ONLY output generated by script, otherwise rest of output will land inside PNG binary, breaking it for sure
Code generated in text mode — as a binary table
$tab = $qr->encode('Test content'); QRspec::debug($tab, true);
Inside bindings/tcpdf you will find slightly modified 2dbarcodes.php. Instal phpqrcode liblaty inside tcpdf folder, then overwrite (or merge) 2dbarcodes.php
Then use similar as example #50 from TCPDF examples:
true, 'padding' => 4, 'fgcolor' => array(0,0,0), 'bgcolor' => false, //array(255,255,255) ); //code name: QR, specify error correction level after semicolon (L,M,Q,H) $pdf->write2DBarcode('PHP QR Code :)', 'QR,L', '', '', 30, 30, $style, 'N');
Uncaught Error: Call to undefined function ImageCreate()
In case this error appears (e.g. in /var/log/apache2/error.log once calling simple_qr.php), the GD library is not ready. Install it
$ sudo apt update && sudo apt install php-gd $ sudo service apache2 restart
This project is based on the work of Dominik Dzienia on http://phpqrcode.sourceforge.net/
Based on C libqrencode library (ver. 3.1.1), Copyright (C) 2006-2010 by Kentaro Fukuchi, http://megaui.net/fukuchi/works/qrencode/index.en.html
QR Code is registered trademarks of DENSO WAVE INCORPORATED in JAPAN and other countries.
Reed-Solomon code encoder is written by Phil Karn, KA9Q. Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
About
PHP library to produce QR Codes
Генерация QR-кода в PHP
Вопрос генерации QR-кодов в PHP достаточно освещён, есть много библиотек, одной из них является «PHP QR Code» – быстрый и легкий класс, рассмотрим его применение совместно с графической библиотекой GD.
Быстрый старт
Вывод в браузер:
require_once __DIR__ . '/phpqrcode/qrlib.php'; QRcode::png('https://snipp.ru/');
Сохранение в файл:
require_once __DIR__ . '/phpqrcode/qrlib.php'; QRcode::png('https://snipp.ru/', __DIR__ . '/qr.png');
Описание параметров
QRcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
$text – текст, который будет закодирован в изображении. $outfile – куда сохранить файл, false – вывести в браузер. $level – уровень коррекции ошибок:
Значение | Уровень | Процент восстановления |
---|---|---|
L | Низкий (по умолчанию) | 7% |
M | Средний | 15% |
Q | Четверть | 25% |
H | Высокий | 30% |
$margin – отступ от краев, задаётся в единицах, указанных в $size . $saveandprint – если true , то изображение одновременно сохранится в файле $outfile и выведется в браузер.
Данные в QR-коде
Для мобильных устройств, в данных можно использовать «протоколы приложений», тем самым при распознавании QR-кода сразу открыть нужное приложение, например набрать телефонный номер, написать письмо, открыть диалог в WhatsApp или Viber и т.д.
Набрать номер телефона:
$text = 'tel:+7903xxxxxxx'; QRcode::png($text);
Написать SMS:
$text = 'sms:+7903xxxxxxx'; QRcode::png($text);
Добавить контакт:
$name = 'Иван Иванов'; $phone = '+7903xxxxxxx'; $text = 'BEGIN:VCARD' . "\n"; $text .= 'FN:' . $name . "\n"; $text .= 'TEL;WORK;VOICE:' . $phone . "\n"; $text .= 'END:VCARD'; QRcode::png($text);
Email:
$text = 'mailto:mail@example.com?subject=Тема письма'; QRcode::png($text);
Мессенджеры:
/* WhatsApp */ $text = 'whatsapp://send?phone=+7903xxxxxxx'; QRcode::png($text); /* Viber */ $text = 'viber://chat?number=+7903xxxxxxx'; QRcode::png($text); /* Skype */ $text = 'skype://логин?call'; QRcode::png($text);
Прозрачный фон
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP', __DIR__ . '/tmp.png', 'M', 6, 2); /* Замена белых пикселей на прозрачный */ $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); $bg_color = imageColorAllocate($im, 0, 0, 0); imagecolortransparent ($im, $bg_color); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 0) < imageSetPixel($im, $x, $y, $bg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Изменить цвет фона
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); /* Цвет фона в RGB */ $bg_color = imageColorAllocate($im, 255, 145, 43); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 0) < imageSetPixel($im, $x, $y, $bg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Изменить цвет пикселей
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); /* Цвет в RGB */ $fg_color = imageColorAllocate($im, 0, 133, 178); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 1) < imageSetPixel($im, $x, $y, $fg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Инверсия цветов
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); imagefilter($im, IMG_FILTER_NEGATE); /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Логотип в центре
Если у QR-кода поднять уровень коррекции ошибок до максимального, то можно спокойно вставить логотип без потери читаемости. Phpqrcode генерирует изображение в формате PNG-8, поэтому потребуется преобразовать его в PNG-24, чтобы избежать потерю цветов у логотипа.
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'H', 6, 2); /* Конвертация PNG8 в PNG24 */ $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); $dst = imagecreatetruecolor($width, $height); imagecopy($dst, $im, 0, 0, 0, 0, $width, $height); imagedestroy($im); /* Наложение логотипа */ $logo = imagecreatefrompng(__DIR__ . '/logo.png'); $logo_width = imagesx($logo); $logo_height = imagesy($logo); $new_width = $width / 3; $new_height = $logo_height / ($logo_width / $new_width); $x = ceil(($width - $new_width) / 2); $y = ceil(($height - $new_height) / 2); imagecopyresampled($dst, $logo, $x, $y, 0, 0, $new_width, $new_height, $logo_width, $logo_height); /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($dst);
Генерируем QR-код на PHP
QR-code, уже давно распространен повсеместно, во всех сферах человеческой жизни. Вроде такая популярная вещь, а нормальной библиотеки (Open Source) на PHP — нет. Товарища deltalab, очень напрягла эта проблема и он решил переписать имеющиеся в наличии С библиотеки ibqrencode от Kentaro Fukuchi, на более привычный ему язык PHP.
PHP QR-Code c открытым исходным кодом (LGPL) библиотека для создание QR code и 2-х мерных штрих-кодов. Базируется на коде ibqrencode библиотеки на C. Обеспечивает API для создания штрихкодов в формате PNG, JPEG с помощью GD2. Реализовано на чистом PHP, без каких-либо внешних зависимостей, кроме конечно GD2.
UPD:
— Что такое QR можно узнать на из Википедии
— Тематический блог на Хабре, где можно постичь масштабы его распространения
— Интересный QR-генератор, с расширенным функционалом PHP QR Code and Data Matrix Generator
— Генератор «красивых» QR, вставка текста в QR mojiq.kazina.com
— Онлайн QR декодер QRDecoder
— Еще одна реализация QR кодирования на Perl+PHP www.swetake.com/qr/qr_cgi_e.html
— QR code плагин для WordPress anton.shevchuk.name/wordpress/qr-code
— PHP-класс для генерации QR-кода от Павла Новицкого www.e-luge.net/blog/full/655063.html
— MX QR code под ExpressionEngine. Базируется на коде от Swetake — MX QR code
— QR-code модуль для Drupal drupal.org/project/qrs_sheets
— Кодируем в QR с помощь Google Charts API
UPD2:
— Самая лучшая считывалка QR-code с экрана BarShow и лучший генератор BarCapture от Jaxo Systems. Написано на Java так-что для пользователей Linux/MacOS в самый раз, есть и бинарники.
— Расширенная утилита для считывания с Web-камеры bcWebCam
— Еще одна считывалка QR-code прямо с экрана, без телефона QuickMark прямая ссылка ~7mb
nzeraf.com