修改擷取驗證碼圖片到本地的PHP程式_PHP教程

來源:互聯網
上載者:User
最近項目不是很大,所以時間比較的空間,昨天琢磨著寫點東西,想起了前幾天電信公司投票選微笑天使的活動,投票是要填寫驗證碼的,想了下想寫個投票作弊程式,可是等我放假回來,人家活動已經結束了,昨天突然想起來,就寫了一個擷取驗證碼圖片到本地的PHP程式,以備今後有類似的投票活動可以直接拿來使用。

程式採用了PHP的GD庫,原理很簡單,就是先建立一張空白圖片,然後把驗證碼的圖片使用PHP GD庫中的imagecreatefromjpeg函數建立一個image對象,最後計算圖片的長寬,再次使用PHP內建的imagecopy複製到一開始建立的空白圖片上去。
全部代碼如下:

Copy to Clipboard引用的內容:[www.bkjia.com]header("Content-type:image/png");
set_time_limit(0);//設定PHP逾時時間
$url = $_GET['url'];
$url = "http://vcer.baidu.com/verify";
$imginfo = GetImageSize ( $url );
$imgw = $imginfo [0];
$imgh = $imginfo [1];
$bg = imagecreatetruecolor($imgw,$imgh);
$image = imagecreatefromjpeg($url);
imagecolorallocate($image,255,255,255);
imagecopy($bg,$image,0,0, 0,0,$imgw,$imgh);
imagedestroy($image);
ImagePng($bg);

此處的代碼支援驗證碼格式為jpg的格式,如果是png或者gif的格式可以參考第二頁。

通過上一頁一個擷取驗證碼圖片到本地的PHP程式,對於驗證碼為jpg格式的圖片是可以正常輸出的,對於png、gif的驗證碼則不能正常使用,今天稍微修改一下PHP代碼,使其可以支援png、gif、jpg三種格式的驗證碼。

PHP判斷圖片的格式可使用php內建的exif_imagetype函數,非常方便,

關於exif_imagetype的詳細使用方法可以訪問:http://php.net/manual/en/function.exif-imagetype.php

代碼:

Copy to Clipboard引用的內容:[www.bkjia.com]header("Content-type:image/png");
set_time_limit(0);//設定PHP逾時時間
$url = $_GET['url'];
$url = "http://vcer.baidu.com/verify";
if(empty($url)){
echo "沒有圖片";
die;
}
$imginfo = GetImageSize ( $url );
$type = exif_imagetype($url);
$imgw = $imginfo [0];
$imgh = $imginfo [1];
$bg = imagecreatetruecolor($imgw,$imgh);
if($type==IMAGETYPE_GIF){
$image = imagecreatefromgif($url);
}elseif($type==IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($url);
}elseif($type==IMAGETYPE_PNG){
$image = imagecreatefrompng($url);
}

imagecolorallocate($image,255,255,255);
imagecopy($bg,$image,0,0, 0,0,$imgw,$imgh);
imagedestroy($image);
ImagePng($bg);

http://www.bkjia.com/PHPjc/364713.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/364713.htmlTechArticle最近項目不是很大,所以時間比較的空間,昨天琢磨著寫點東西,想起了前幾天電信公司投票選微笑天使的活動,投票是要填寫驗證碼的,...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.