目前绝大多数 PHP 程序员使用面向过程的方式, 因为解析 web 页面本身就非常过程化 (从一个标签到另一个标签) 在 html 中嵌入过程处理代码是很直接自然的作法, 所以 PHP 程序员通常使用这种方式
如果你是刚接触 PHP, 用面向过程的风格来书写代码很可能是你唯一的选择但是如果你经常上 PHP 论坛和新闻组的话, 你应该会看到有关对象的文章你也可能看到过如何书写面向对象的 PHP 代码的教程或者你也可能下载过一些现成的类库, 并尝试着去实例化其中的对象和使用类方法 -- 尽管你可能没有真正理解这些类为什么可以工作, 或者为什么需要使用面向对象的方法来实现功能
应该使用面向对象的风格还是面向过程的风格? 双方各有支持者像对象是低效的或对象非常棒这样的议论也时有耳闻本文不尝试轻易判定两种方法的哪种具有绝对的优势, 而是要找出每种方法的优缺点
1: 面向对象的实现利用 php 给图片添加水印方法
- class Image_class {
- private $image;
- private $info;
- /**
- * @param $src: 图片路径
- * 加载图片到内存中
- */
- function __construct($src) {
- $info = getimagesize($src);
- $type = image_type_to_extension($info[2], false);
- $this - >info = $info;
- $this - >info['type'] = $type;
- $fun = "imagecreatefrom".$type;
- $this - >image = $fun($src);
- }
- /**
- * @param $fontsize: 字体大小
- * @param $x: 字体在图片中的 x 位置
- * @param $y: 字体在图片中的 y 位置
- * @param $color: 字体的颜色是一个包含 rgba 的数组
- * @param $text: 想要添加的内容
- * 操作内存中的图片, 给图片添加文字水印
- */
- public
- function fontMark($fontsize, $x, $y, $color, $text) {
- $col = imagecolorallocatealpha($this - >image, $color[0], $color[1], $color[2], $color[3]);
- imagestring($this - >image, $fontsize, $x, $y, $text, $col);
- }
- /*
- * 输出图片到浏览器中
- */
- public
- function show() {
- header('content-type:'.$this - >info['mime']);
- $fun = 'image'.$this - >info['type'];
- $fun($this - >image);
- }
- /**
- * 销毁图片
- */
- function __destruct() {
- imagedestroy($this - >image);
- }
- }
- // 对类的调用
- $obj = new Image_class('001.png');
- $obj - >fontMark(20, 20, 30, array(255, 255, 255, 60), 'hello');
- $obj - >show();
2: 面向过程的编写利用 php 给图片添加水印方法:
- // 指定图片路径
- $src = '001.png';
- // 获取图片信息
- $info = getimagesize($src);
- // 获取图片扩展名
- $type = image_type_to_extension($info[2],false);
- // 动态的把图片导入内存中
- $fun = "imagecreatefrom{$type}";
- $image = $fun('001.png');
- // 指定字体颜色
- $col = imagecolorallocatealpha($image,255,255,255,50);
- // 指定字体内容
- $content = 'helloworld';
- // 给图片添加文字
- imagestring($image,5,20,30,$content,$col);
- // 指定输入类型
- header('Content-type:'.$info['mime']);
- // 动态的输出图片到浏览器中
- $func = "image{$type}";
- $func($image);
- // 销毁图片
- imagedestroy($image);
以上代码示例是介绍 php 面向对象与面向过程两种方法给图片添加文字水印, 希望大家喜欢
来源: https://www.php1.cn/detail/php-58913826f4.html