常用的php图片处理类(水
这篇文章主要汇总介绍了两个常用的php图片处理类(水
常用的php图片处理类(水印、等比缩放、固定高宽)分享
typeList = array(1=>'gif',2=>'jpg',3=>'png'); $ginfo = getimagesize($source); $this->source_width = $ginfo[0]; $this->source_height = $ginfo[1]; $this->source_type_id = $ginfo[2]; $this->orign_url = $source; $this->orign_name = basename($source); $this->orign_dirname = dirname($source); } //判断图片的文件的格式,返回PHP可识别的编码 public function judgeType($type,$source){ if($type == 1){ return imagecreatefromgif($source); //gif }else if($type == 2){ return imagecreatefromjpeg($source); //jpg }else if($type == 3){ return imagecreatefrompng($source); //png }else{ return false; } } //生成水印图片 public function waterMakeImage($logo){ $linfo = getimagesize($logo); $logo_width = $linfo[0]; $logo_height = $linfo[1]; $logo_type_id = $linfo[2]; $sourceHandle = $this->judgeType($this->source_type_id,$this->orign_url); $logoHandle = $this->judgeType($logo_type_id,$logo); if(!$sourceHandle || !$logoHandle){ return false; } $x = ($this->source_width - $logo_width)/2; $y = ($this->source_height - $logo_height)/2; imagecopy($sourceHandle,$logoHandle,$x,$y,0,0,$logo_width,$logo_height); $newPic = $this->orign_dirname.'\water_'.time().'.'.$this->typeList[$this->source_type_id]; if($this->saveImage($sourceHandle,$newPic)){ imagedestroy($sourceHandle); imagedestroy($logoHandle); } } //固定高度宽度 public function fixSizeImage($width,$height){ if($width > $this->source_width) $this->source_width; if($height > $this->source_height) $this->source_height; if($width === false){ $width = floor($this->source_width / ($this->source_height / $height)); } if($height === false){ $height = floor($this->source_height / ($this->source_width / $width)); } $this->tinyImage($width,$height); } //等比例缩放图片 public function scaleImage($scale){ $width = floor($this->source_width * $scale); $height = floor($this->source_height * $scale); $this->tinyImage($width, $height); } //创建缩略图 public function tinyImage($width,$height){ $tinyImage = imagecreatetruecolor($width,$height); $handle = $this->judgeType($this->source_type_id,$this->orign_url); if(function_exists('imagecopyresampled')){ imagecopyresampled($tinyImage, $handle, 0, 0, 0, 0, $width, $height, $this->source_width, $this->source_height); }else{ imagecopyresized($tinyImage, $handle, 0, 0, 0, 0, $width, $height, $this->source_width, $this->source_height); } $newPic = $this->orign_dirname.'\thumb_'.time().'_'.$width."_".$height.".".$this->typeList[$this->source_type_id]; if($this->saveImage($tinyImage,$newPic)){ imagedestroy($tinyImage); imagedestroy($handle); } } //保存图片 private function saveImage($image,$url){ if(imagejpeg($image,$url)){ return true; } } } $imgHandle = new Image_process('D:\AppServ\www\test\getimg\14061907445601.jpg'); //$imgHandle->waterMakeImage('D:\AppServ\www\test\getimg\shougongke.png'); //生成水印图片 //$imgHandle->fixSizeImage(200,150); //固定长度图片 $imgHandle->scaleImage(0.2); //等比例缩放 ?>
示例二:
xx,'height'=>xxx) * @internal * 我们一般的压缩图片方法,在图片过长或过宽时生成的图片 * 都会被“压扁”,针对这个应采用先裁剪后按比例压缩的方法 */ public function thumb_img($src_img, $save_img = '', $option) { if (empty ( $option ['width'] ) or empty ( $option ['height'] )) { return array ('flag' => False, 'msg' => '原图长度与宽度不能小于0' ); } $org_ext = $this->is_img ( $src_img ); if (! $org_ext ['flag']) { return $org_ext; } //如果有保存路径,则确定路径是否正确 if (! empty ( $save_img )) { $f = $this->check_dir ( $save_img ); if (! $f ['flag']) { return $f; } } //获取出相应的方法 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] ); //获取原大小 $source = $org_funcs ['create_func'] ( $src_img ); $src_w = imagesx ( $source ); $src_h = imagesy ( $source ); //调整原始图像(保持图片原形状裁剪图像) $dst_scale = $option ['height'] / $option ['width']; //目标图像长宽比 $src_scale = $src_h / $src_w; // 原图长宽比 if ($src_scale >= $dst_scale) { // 过高 $w = intval ( $src_w ); $h = intval ( $dst_scale * $w ); $x = 0; $y = ($src_h - $h) / 3; } else { // 过宽 $h = intval ( $src_h ); $w = intval ( $h / $dst_scale ); $x = ($src_w - $w) / 2; $y = 0; } // 剪裁 $croped = imagecreatetruecolor ( $w, $h ); imagecopy ( $croped, $source, 0, 0, $x, $y, $src_w, $src_h ); // 缩放 $scale = $option ['width'] / $w; $target = imagecreatetruecolor ( $option ['width'], $option ['height'] ); $final_w = intval ( $w * $scale ); $final_h = intval ( $h * $scale ); imagecopyresampled ( $target, $croped, 0, 0, 0, 0, $final_w, $final_h, $w, $h ); imagedestroy ( $croped ); //输出(保存)图片 if (! empty ( $save_img )) { $org_funcs ['save_func'] ( $target, $save_img ); } else { header ( $org_funcs ['header'] ); $org_funcs ['save_func'] ( $target ); } imagedestroy ( $target ); return array ('flag' => True, 'msg' => '' ); } /** * * 等比例缩放图像 * @param $src_img 原图片 * @param $save_img 需要保存的地方 * @param $option 参数设置 array('width'=>xx,'height'=>xxx) * */ function resize_image($src_img, $save_img = '', $option) { $org_ext = $this->is_img ( $src_img ); if (! $org_ext ['flag']) { return $org_ext; } //如果有保存路径,则确定路径是否正确 if (! empty ( $save_img )) { $f = $this->check_dir ( $save_img ); if (! $f ['flag']) { return $f; } } //获取出相应的方法 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] ); //获取原大小 $source = $org_funcs ['create_func'] ( $src_img ); $src_w = imagesx ( $source ); $src_h = imagesy ( $source ); if (($option ['width'] && $src_w > $option ['width']) || ($option ['height'] && $src_h > $option ['height'])) { if ($option ['width'] && $src_w > $option ['width']) { $widthratio = $option ['width'] / $src_w; $resizewidth_tag = true; } if ($option ['height'] && $src_h > $option ['height']) { $heightratio = $option ['height'] / $src_h; $resizeheight_tag = true; } if ($resizewidth_tag && $resizeheight_tag) { if ($widthratio True, 'msg' => '' ); } /** * * 生成水印图片 * @param $org_img 原图像 * @param $mark_img 水印标记图像 * @param $save_img 当其目录不存在时,会试着创建目录 * @param array $option 为水印的一些基本设置包含: * x:水印的水平位置,默认为减去水印图宽度后的值 * y:水印的垂直位置,默认为减去水印图高度后的值 * alpha:alpha值(控制透明度),默认为50 */ public function water_mark($org_img, $mark_img, $save_img = '', $option = array()) { //检查图片 $org_ext = $this->is_img ( $org_img ); if (! $org_ext ['flag']) { return $org_ext; } $mark_ext = $this->is_img ( $mark_img ); if (! $mark_ext ['flag']) { return $mark_ext; } //如果有保存路径,则确定路径是否正确 if (! empty ( $save_img )) { $f = $this->check_dir ( $save_img ); if (! $f ['flag']) { return $f; } } //获取相应画布 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] ); $org_img_im = $org_funcs ['create_func'] ( $org_img ); $mark_funcs = $this->get_img_funcs ( $mark_ext ['msg'] ); $mark_img_im = $mark_funcs ['create_func'] ( $mark_img ); //拷贝水印图片坐标 $mark_img_im_x = 0; $mark_img_im_y = 0; //拷贝水印图片高宽 $mark_img_w = imagesx ( $mark_img_im ); $mark_img_h = imagesy ( $mark_img_im ); $org_img_w = imagesx ( $org_img_im ); $org_img_h = imagesx ( $org_img_im ); //合成生成点坐标 $x = $org_img_w - $mark_img_w; $org_img_im_x = isset ( $option ['x'] ) ? $option ['x'] : $x; $org_img_im_x = ($org_img_im_x > $org_img_w or $org_img_im_x $org_img_h or $org_img_im_y 100 or $alpha True, 'msg' => '' ); } /** * * 检查图片 * @param unknown_type $img_path * @return array('flag'=>true/false,'msg'=>ext/错误信息) */ private function is_img($img_path) { if (! file_exists ( $img_path )) { return array ('flag' => False, 'msg' => "加载图片 $img_path 失败!" ); } $ext = explode ( '.', $img_path ); $ext = strtolower ( end ( $ext ) ); if (! in_array ( $ext, $this->exts )) { return array ('flag' => False, 'msg' => "图片 $img_path 格式不正确!" ); } return array ('flag' => True, 'msg' => $ext ); } /** * * 返回正确的图片函数 * @param unknown_type $ext */ private function get_img_funcs($ext) { //选择 switch ($ext) { case 'jpg' : $header = 'Content-Type:image/jpeg'; $createfunc = 'imagecreatefromjpeg'; $savefunc = 'imagejpeg'; break; case 'jpeg' : $header = 'Content-Type:image/jpeg'; $createfunc = 'imagecreatefromjpeg'; $savefunc = 'imagejpeg'; break; case 'gif' : $header = 'Content-Type:image/gif'; $createfunc = 'imagecreatefromgif'; $savefunc = 'imagegif'; break; case 'bmp' : $header = 'Content-Type:image/bmp'; $createfunc = 'imagecreatefrombmp'; $savefunc = 'imagebmp'; break; default : $header = 'Content-Type:image/png'; $createfunc = 'imagecreatefrompng'; $savefunc = 'imagepng'; } return array ('save_func' => $savefunc, 'create_func' => $createfunc, 'header' => $header ); } /** * * 检查并试着创建目录 * @param $save_img */ private function check_dir($save_img) { $dir = dirname ( $save_img ); if (! is_dir ( $dir )) { if (! mkdir ( $dir, 0777, true )) { return array ('flag' => False, 'msg' => "图片保存目录 $dir 无法创建!" ); } } return array ('flag' => True, 'msg' => '' ); } } if (! empty ( $_FILES ['test'] ['tmp_name'] )) { //例子 $img = new Img (); //原图 $name = explode ( '.', $_FILES ['test'] ['name'] ); $org_img = 'D:/test.' . end ( $name ); move_uploaded_file ( $_FILES ['test'] ['tmp_name'], $org_img ); $option = array ('width' => $_POST ['width'], 'height' => $_POST ['height'] ); if ($_POST ['type'] == 1) { $s = $img->resize_image ( $org_img, '', $option ); } else { $img->thumb_img ( $org_img, '', $option ); } unlink ( $org_img ); }
以上所述就是本文的全部内容了,,希望大家能够喜欢。

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

PHP 8.4 apporte plusieurs nouvelles fonctionnalités, améliorations de sécurité et de performances avec une bonne quantité de dépréciations et de suppressions de fonctionnalités. Ce guide explique comment installer PHP 8.4 ou mettre à niveau vers PHP 8.4 sur Ubuntu, Debian ou leurs dérivés. Bien qu'il soit possible de compiler PHP à partir des sources, son installation à partir d'un référentiel APT comme expliqué ci-dessous est souvent plus rapide et plus sécurisée car ces référentiels fourniront les dernières corrections de bogues et mises à jour de sécurité à l'avenir.

Si vous êtes un développeur PHP expérimenté, vous aurez peut-être le sentiment d'y être déjà allé et de l'avoir déjà fait. Vous avez développé un nombre important d'applications, débogué des millions de lignes de code et peaufiné de nombreux scripts pour réaliser des opérations.

Visual Studio Code, également connu sous le nom de VS Code, est un éditeur de code source gratuit – ou environnement de développement intégré (IDE) – disponible pour tous les principaux systèmes d'exploitation. Avec une large collection d'extensions pour de nombreux langages de programmation, VS Code peut être c

JWT est une norme ouverte basée sur JSON, utilisée pour transmettre en toute sécurité des informations entre les parties, principalement pour l'authentification de l'identité et l'échange d'informations. 1. JWT se compose de trois parties: en-tête, charge utile et signature. 2. Le principe de travail de JWT comprend trois étapes: la génération de JWT, la vérification de la charge utile JWT et l'analyse. 3. Lorsque vous utilisez JWT pour l'authentification en PHP, JWT peut être généré et vérifié, et les informations sur le rôle et l'autorisation des utilisateurs peuvent être incluses dans l'utilisation avancée. 4. Les erreurs courantes incluent une défaillance de vérification de signature, l'expiration des jetons et la charge utile surdimensionnée. Les compétences de débogage incluent l'utilisation des outils de débogage et de l'exploitation forestière. 5. L'optimisation des performances et les meilleures pratiques incluent l'utilisation des algorithmes de signature appropriés, la définition des périodes de validité raisonnablement,

Ce tutoriel montre comment traiter efficacement les documents XML à l'aide de PHP. XML (Language de balisage extensible) est un langage de balisage basé sur le texte polyvalent conçu à la fois pour la lisibilité humaine et l'analyse de la machine. Il est couramment utilisé pour le stockage de données et

Une chaîne est une séquence de caractères, y compris des lettres, des nombres et des symboles. Ce tutoriel apprendra à calculer le nombre de voyelles dans une chaîne donnée en PHP en utilisant différentes méthodes. Les voyelles en anglais sont a, e, i, o, u, et elles peuvent être en majuscules ou en minuscules. Qu'est-ce qu'une voyelle? Les voyelles sont des caractères alphabétiques qui représentent une prononciation spécifique. Il y a cinq voyelles en anglais, y compris les majuscules et les minuscules: a, e, i, o, u Exemple 1 Entrée: String = "TutorialSpoint" Sortie: 6 expliquer Les voyelles dans la chaîne "TutorialSpoint" sont u, o, i, a, o, i. Il y a 6 yuans au total

Liaison statique (statique: :) implémente la liaison statique tardive (LSB) dans PHP, permettant à des classes d'appel d'être référencées dans des contextes statiques plutôt que de définir des classes. 1) Le processus d'analyse est effectué au moment de l'exécution, 2) Recherchez la classe d'appel dans la relation de succession, 3) il peut apporter des frais généraux de performance.

Quelles sont les méthodes magiques de PHP? Les méthodes magiques de PHP incluent: 1. \ _ \ _ Construct, utilisé pour initialiser les objets; 2. \ _ \ _ Destruct, utilisé pour nettoyer les ressources; 3. \ _ \ _ Appel, gérer les appels de méthode inexistants; 4. \ _ \ _ GET, Implémentez l'accès à l'attribut dynamique; 5. \ _ \ _ SET, Implémentez les paramètres d'attribut dynamique. Ces méthodes sont automatiquement appelées dans certaines situations, améliorant la flexibilité et l'efficacité du code.
