处理图片储备知识

在创建图像处理类的前面总结一下需要的知识点:

1 图片的输出和生成

<?php
//载入一张图片,创建一张新图片(以3.jpg创建了一张新图,然后处理输出)
$img = imagecreatefromjpeg('1.jpg');
//指定编码格式,否则回事乱码的
header('Content-Type:image/jpeg');
//输出图片:第二个参数是保存地址,没有就是在浏览器输出
imagejpeg($img,'action/11.jpg');
//销毁资源
imagedestroy($img);
?>

2 获取图片宽和高

<?php
//获取图片的长和高getimagesize()
list($width,$height,$type) = getimagesize('1.jpg');//返回的是数组,可以打印出来看看
echo $width;
echo $height;
echo $type;
?>

3 按百分比缩放

<?php
$img = imagecreatefromjpeg('1.jpg');//创建图像
list($width,$height,$type) = getimagesize('1.jpg');//获取宽高和类型

//按百分比显示
$per = 0.3;
$new_width = $width*$per;
$new_height = $height*$per;
//创建图像,用上缩放后的大小
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($new, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);//两种方法,第二个比第一个图片质量好
imagecopyresampled($new, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-Type:image/jpeg');
imagejpeg($new);
imagedestroy($img);
imagedestroy($new);
?>

4 按等比例缩放

<?php
$img = imagecreatefromjpeg('1.jpg');//创建图像
list($width,$height,$type) = getimagesize('1.jpg');//获取宽高和类型

//按等比例显示
$new_width = 150;
$new_height = 50;
//等比例运算公式
if ($width<$height){
    $new_width = ($new_height/$height)*$width;
}else {
    $new_height = ($new_width/$width)*$height;
}

//创建图像,用上缩放后的大小
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-Type:image/jpeg');
imagejpeg($new);
imagedestroy($img);
imagedestroy($new);
?>

5 图像裁剪

<?php
$img = imagecreatefromjpeg('1.jpg');//创建图像
list($width,$height,$type) = getimagesize('1.jpg');//获取宽高和类型
$new_width = 150;
$new_height = 50;
if ($width<$height){
    $new_width = ($new_height/$height)*$width;
}else {
    $new_height = ($new_width/$width)*$height;
}
$new = imagecreatetruecolor($new_width, $new_height);

//裁剪,裁剪可能会漏出背景所以要把背景填充起来
imagecopyresampled($new, $img, 0, 0, 50, 50, $new_width+50, $new_height+50, $width, $height);

header('Content-Type:image/jpeg');
imagejpeg($new);
imagedestroy($img);
imagedestroy($new);
?>

6 加水印

<?php
$img = imagecreatefromjpeg('1.jpg');//创建图像

//1 文本水印
$color = imagecolorallocate($img, 0, 0, 0);
imagettftext($img, 10, 0, 10, 10, $color, 'font/elephant.ttf', 'DXM');
//2 图片水印
$mark = imagecreatefrompng('yc.png');//载入水印图片
imagecopy($img, $mark, 0, 0, 0, 0, 82, 12);

header('Content-Type:image/jpeg');
imagejpeg($img);
imagedestroy($img);
?>

 

posted @ 2017-01-14 15:14  党兴明  阅读(184)  评论(0编辑  收藏  举报