上圖中的二維碼,看起來跟普通的黑白二維碼不同,怎樣生成?本文簡單介紹這類「視覺二維碼」的生成算法,供你們聊流。php
前置閱讀資料:
1.什麼是二維碼 -->http://baike.baidu.com/view/132241.htm
2.二維碼生成的php開源庫(稍後給出)
3.demo地址-->http://visual.2weima.com/算法
OK,下面進入正文:segmentfault
字符串轉換成[1,1,1,1,0,0.....0,1]陣列的過程本文不討論,由已經開源多年的QR庫負責轉換。數組
咱們須要在PHP程序(或其餘程序語言中)調用QR庫,並封裝以下的function:服務器
getFrame($str){ ...... return Array( {1,1,1,1,1,1,1,0,1,0,......,1,0}, {1,1,1,1,1,1,1,0,1,0,......,1,0}, {0,1,0,1,1,1,1,0,1,0,......,1,0}, ...... ...... {1,1,1,1,1,1,1,0,1,0,......,1,1} ) }
那麼,轉換以後的二維碼原始數據,就是這樣一個二維數組對象。調用PHP的GD庫(或其餘語言對應的圖形庫),根據上述二維數組作循環輸出正方形圖形的操做,‘1’輸出黑色正方形,‘0’輸出白色正方形,正方形的位置由二維數組對應的下標肯定,因而能夠得出以下的常規二維碼圖片:
this
$frame = getFrame("hello world"); $h = count($frame); $w = strlen($frame[0]); $pixelPerPoint = 15; //每一個色塊15像素 $imgW = $w * $pixelPerPoint; //圖片寬度 $imgH = $h * $pixelPerPoint; //圖片高度 $base_image = imagecreate($imgW, $imgH); $bgc = imagecolorallocate($base_image,255,255,255); //背景色白色 /////////////////////////////////////////////////////////// $col = imagecolorallocate($base_image,0,0,0);//前景色 for($y=0; $y<$h; $y++) { for($x=0; $x<$w; $x++) { if ($frame[$y][$x] == '1'){ imagefilledrectangle($base_image,($x)* $pixelPerPoint,($y) * $pixelPerPoint,($x + 1 )* $pixelPerPoint,($y+ 1) * $pixelPerPoint,$col); } } }
這裏用開源庫和簡單的方法,能在本身的服務器端生成普通的黑白方塊二維碼了,接下來嘗試改變二維碼的顏色:spa
$col = imagecolorallocate($base_image,255,0,0);//前景色設置成紅色
簡單的將前景色設置成(255,0,0),紅色二維碼就成功生成了code
接下來再嘗試改變一下方塊顏色,讓顏色與方塊的座標關聯起來,注意RGB顏色的範圍是0-255,不要超過這個範圍:htm
for($y=0; $y<$h; $y++) { for($x=0; $x<$w; $x++) { if ($frame[$y][$x] == '1'){ $col = imagecolorallocate($base_image,100 + $y * 4,50 + $x * 3,30);//顏色與座標關聯 imagefilledrectangle($base_image,($x)* $pixelPerPoint + $this->l,($y) * $pixelPerPoint + $this->t,($x + 1 )* $pixelPerPoint + $this->l,($y+ 1) * $pixelPerPoint + $this->t,$col); } } }
這樣就實現了一個顏色漸變的彩色二維碼,是否是開始變得有意思了?對象
讓咱們繼續:給二維碼加一個背景圖片
$base_image = imagecreatefrompng("bg.png");
將$base_image對象用GD庫的imagecreatefrompng方法來建立,很是easy,預覽效果以下:
目前爲止實現了改變二維碼方塊顏色和設置二維碼背景圖片,這只是第一步,讓咱們繼續下一章節。
(未完待續...)