简单缩略图
<?php
//创建原图画布和缩略图画布
$src_file = './src.jpg';
$src_img = imagecreatefromjpeg($src_file);//基于已有图片创建
//缩略图的大小应该如何确定?
$dst_img = imagecreatetruecolor(100, 100);//创建一个新的画布
//采样,拷贝,修改大小
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, 100, 100, 500, 375);
//导出
header('Content-Type:image/jpeg');
imagejpeg($dst_img);
//销毁
imagedestroy($dst_img);
imagedestroy($src_img);
等比缩略图
<?php
//已知条件
$max_w = 100;//范围的最大的宽
$max_h = 100;//范围的最大的高
$src_file = './src.jpg';//原始图片
//计算原图的宽高
$src_info = getimagesize($src_file);
$src_w = $src_info[0];//原图宽
$src_h = $src_info[1];//原图高
//比较 宽之比 与 高之比
if($src_w/$max_w > $src_h/$max_h) {
//宽应该缩放的多
$dst_w = $max_w;//缩略图的宽为范围的宽
$dst_h = $src_h/$src_w * $dst_w;//按照原图的宽高比将求出缩略图高
} else {
$dst_h = $max_h;
$dst_w = $src_w/$src_h * $dst_h;
}
//创建画布
$src_img = imagecreatefromjpeg($src_file);//基于已有图片创建
//缩略图的大小应该如何确定?
$dst_img = imagecreatetruecolor($dst_w, $dst_h);//创建一个新的画布
//采样,拷贝,修改大小
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
//导出
header('Content-Type:image/jpeg');
imagejpeg($dst_img);
//销毁
imagedestroy($dst_img);
imagedestroy($src_img);
水印
<?php
$dst_file = './dst.jpg';
$stamp_file = './stamp.jpg';
//画布
$dst_img = imagecreatefromjpeg($dst_file);
$stamp_img = imagecreatefromjpeg($stamp_file);
//合并,拷贝
imagecopymerge($dst_img, $stamp_img, 0, 0, 0, 0, 128, 52, 70);
//
header('Content-Type: image/jpeg');
imagejpeg($dst_img);
imagedestroy($dst_img);
imagedestroy($stamp_img);
验证码
<?php
//require '111.php';
$rand_bg_file = './captcha/captcha_bg' . mt_rand(1, 5) . '.jpg';
//echo $rand_bg_file;
//创建画布
$img = imagecreatefromjpeg($rand_bg_file);
//绘制边框
$white = imagecolorallocate($img, 0xff, 0xff, 0xff);
//不填充矩形
imagerectangle($img, 0, 0, 144, 19, $white);
//写码值
//生成码值,随机的4个只包含大写字母,和数字的字符串!
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';//32 个字符
//随机取4个
$captcha_str = '';
for($i=1,$strlen=strlen($chars); $i<=4; ++$i) {
$rand_key = mt_rand(0, $strlen-1);
$captcha_str .= $chars[$rand_key];
}
//保存到session中
@session_start();
$_SESSION['captcha_code'] = $captcha_str;
//echo $captcha_str;
//写
//先确定颜色,白黑随机!
$black = imagecolorallocate($img, 0, 0, 0);
if(mt_rand(0, 1) == 1 ) {
$str_color = $white;
} else {
$str_color = $black;
}
imagestring($img, 5, 60, 3, $captcha_str, $str_color);
//保存
//imagejpeg($img, './captcha.jpg');//输出到文件内!
//告知浏览器,发送的是jpeg格式的图片
header('Content-Type: image/jpeg; charset=utf-8');
//echo 'itcast';
imagejpeg($img);//输出到浏览器端!
//销毁资源
imagedestroy($img);