php code sharing for generating thumbnails by percentage

  • 2021-06-28 08:51:36
  • OfStack

So I turned over a manual, understood several functions, and wrote a simple php thumbnail generation program.Without classes, I think one function will do it, and it's easier for beginners to understand, so it can help more people.

Supports ratio-by-score abbreviations, length-by-width abbreviations as specified, and percentage by default.Comments in the program are already detailed. If you have any questions, you can leave a message below. Welcome to communicate with me.

The source code is as follows:


<?php

 /*
  * param ori_img  Name and path of the original image 
  * param new_img  Name of generated image 
  * param percent  Indicates that the thumbnails are based on the percentage of the original image. When this item is empty, the default is 50%
  * param width  Specify width after thumbnail 
  * param height  Specify the height after the thumbnail 
  * 
  *  Note: When  percent width height  When all values are passed in, and percent>0 When preferred, abbreviate by percentage 
  * by : https://www.ofstack.com  Share more sources with you 
  *  Warm Tip: Use this feature in php.ini Medium Open  gd2
  *
  **/

 function makeThumb($ori_img, $new_img, $percent=50, $width=0, $height=0){

  $original = getimagesize($ori_img); // To get information about the picture, you can print_r($original) Finding it is 1 Arrays 
  //$original[2] Is the type of picture where 1 Express gif , 2 Express jpg , 3 Express png
  switch($original[2]){
   case 1 : $s_original = imagecreatefromgif($ori_img);
    break;
   case 2 : $s_original = imagecreatefromjpeg($ori_img);
    break;
   case 3 : $s_original = imagecreatefrompng($ori_img);
    break;
  }

  if($percent > 0){
   $width = $original[0] * $percent / 100;
   $width = ($width > 0) ? $width : 1;
   $height = $original[1] * $percent / 100;
   $height = ($height > 0) ? $height : 1;
  }

  // Establish 1 True color canvas 
  $canvas = imagecreatetruecolor($width,$height);
  imagecopyresized($canvas, $s_original, 0, 0, 0, 0, $width, $height, $original[0], $original[1]);
  //header("Content-type:image/jpeg");
  //imagejpeg($canvas); // Output Picture to Browser 
  $loop = imagejpeg($canvas, $new_img); // Generate a new picture 
  if($loop){
   echo "OK!<br/>";
  }
 }

 makeThumb("bhsj.jpg","suolue1.jpg",15,0,0); // Generate the original map 15% Thumbnails of 
 makeThumb("bhsj.jpg","suolue2.jpg",0,200,120); // Generate Width As 100px, High to 60px Thumbnails of 
 makeThumb("bhsj.jpg","suolue3.jpg",15,200,120); // Generate the original map 15% Thumbnails of (% takes precedence when all parameters are filled) 

?>


Related articles: