在信息时代,数据就是一种宝贵资源。公司网站的展示页有许多用户的手机号码,但是为了防止竞争对手采集电话号码信息或者说提高他们采集数据的难度。于是就有了电话号码以图片格式输出的这个需求。下面已yii为例讲解:
php代码:
class SiteController extends Controller
{
public function actionGetPhone($id)
{
//从redis缓存里面读取数据,你可以根据你的实际情况读取数据
$redis = new RedisCache;
$res = $redis->getInfo($id, $this->id);
if (!$res) {
Yii::app()->end();
}
$res = json_decode($res['model'], TRUE);
//end
header("Cache-Control: private, max-age=10800, pre-check=10800");
header("Pragma: private");
header("Expires: " . date(DATE_RFC822, strtotime(" 1 year")));
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
(strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $res['update_time'])) {
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $res['update_time']) . ' GMT', TRUE, 304);
Yii::app()->end();
}
$phone = explode(',', $res['phone']);
/*
* This page creates a simple image.
* The image makes use of a TrueType font.
*/
// Establish image factors:
$text = $phone[0];
$font_size = Yii::app()->request->getParam('fs'); // Font size is in pixels.
if (!$font_size) {
$font_size = 14;
}
$font_file = Yii::app()->basePath . '/data/Georgia.ttf'; // This is the path to your font file.
// Retrieve bounding box:
$type_space = imagettfbbox($font_size, 0, $font_file, $text);
// Determine image width and height, 10 pixels are added for 5 pixels padding:
$image_width = abs($type_space[4] - $type_space[0]) + 2;
$image_height = abs($type_space[5] - $type_space[1]) + 2;
// Create image:
$image = imagecreatetruecolor($image_width, $image_height);
// Allocate text and background colors (RGB format):
$text_colors = Yii::app()->request->getParam('fc');//文本颜色
if ($text_colors) {
$text_colors = explode(',', $text_colors);
} else {
$text_colors = array(0, 0, 0);
}
$bg_colors = Yii::app()->request->getParam('bc');//背景颜色
if ($bg_colors) {
$bg_colors = explode(',', $bg_colors);
} else {
$bg_colors = array(255, 255, 255);
}
$text_color = imagecolorallocate($image, $text_colors[0], $text_colors[1], $text_colors[2]);
$bg_color = imagecolorallocate($image, $bg_colors[0], $bg_colors[1], $bg_colors[2]);
// Fill image:
imagefill($image, 0, 0, $bg_color);
// Fix starting x and y coordinates for the text:
$x = 0; // Padding of 5 pixels.
$y = $image_height - 5; // So that the text is vertically centered.
// Add TrueType text to image:
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
header('Content-type:image/png');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $res['update_time']) . ' GMT');
imagepng($image);
imagedestroy($image);
}
}
html代码:
<a style="cursor:default;padding-left: 25px;">
<img class="serve-master-number">
</a>
js代码:
这里是js异步请求的方式加载。
//电话号码以图片格式输出
$('.serve-master-number').attr('src', '<?php echo Yii::app()->request->baseUrl; ?>/site/getPhone/id/<?php echo $value['masterInfo']['master_id'] ?>/fs/14/fc/254,143,0/bc/255,255,255');