Home Backend Development PHP Tutorial Two examples of image compression in PHP

Two examples of image compression in PHP

Jul 25, 2016 am 08:52 AM

  1. /**
  2. * desription compressed image
  3. * @param sting $imgsrc image path
  4. * @param string $imgdst save path after compression
  5. */
  6. function image_png_size_add($imgsrc,$imgdst){
  7. list($width,$height,$type)=getimagesize($imgsrc);
  8. $new_width = ($width>600?600:$width)*0.9;
  9. $new_height =($height>600?600:$height)*0.9;
  10. switch($type){
  11. case 1:
  12. $giftype=check_gifcartoon($imgsrc);
  13. if($giftype){
  14. header('Content-Type:image/gif');
  15. $image_wp=imagecreatetruecolor($new_width, $new_height);
  16. $image = imagecreatefromgif($imgsrc);
  17. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  18. imagejpeg($image_wp, $imgdst,75);
  19. imagedestroy($image_wp);
  20. }
  21. break;
  22. case 2:
  23. header('Content-Type:image/jpeg');
  24. $image_wp=imagecreatetruecolor($new_width, $new_height);
  25. $image = imagecreatefromjpeg($imgsrc);
  26. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  27. imagejpeg($image_wp, $imgdst,75);
  28. imagedestroy($image_wp);
  29. break;
  30. case 3:
  31. header('Content-Type:image/png');
  32. $image_wp=imagecreatetruecolor($new_width, $new_height);
  33. $image = imagecreatefrompng($imgsrc);
  34. imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  35. imagejpeg($image_wp, $imgdst,75);
  36. imagedestroy($image_wp);
  37. break;
  38. } // bbs.it-home.org
  39. }
  40. /**
  41. * desription determines whether it is a gif animation
  42. * @param sting $image_file image path
  43. * @return boolean t yes f no
  44. */
  45. function check_gifcartoon($image_file){
  46. $fp = fopen($image_file,'rb');
  47. $image_head = fread($fp,1024);
  48. fclose($fp);
  49. return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
  50. }
  51. ?>
复制代码

Example 2:

  1. /*
  2. Function: Adjust image size or generate thumbnails
  3. Return: True/False
  4. Parameters:
  5. $Image The image that needs to be adjusted (including path)
  6. $Dw=450 when adjusting Maximum width; absolute width when thumbnailing
  7. $Dh=450 Maximum height when adjusting; absolute height when thumbnailing
  8. $Type=1 1, adjust size; 2, generate thumbnail
  9. $path='img/';/ /path
  10. $phtypes=array(
  11. 'img/gif',
  12. 'img/jpg',
  13. 'img/jpeg',
  14. 'img/bmp',
  15. 'img/pjpeg',
  16. 'img/x-png '
  17. );
  18. Function Img($Image,$Dw=450,$Dh=450,$Type=1){
  19. IF(!File_Exists($Image)){
  20. Return False;
  21. }
  22. //Generate if necessary Thumbnail, copy the original image and re-assign it to $Image
  23. IF($Type!=1){
  24. Copy($Image,Str_Replace(".","_x.",$Image));
  25. $Image= Str_Replace(".","_x.",$Image);
  26. }
  27. //Get the file type and create different objects according to different types
  28. $ImgInfo=GetImageSize($Image);
  29. Switch($ImgInfo[2 ]){
  30. Case 1:
  31. $Img = @ImageCreateFromGIF($Image);
  32. Break;
  33. Case 2:
  34. $Img = @ImageCreateFromJPEG($Image);
  35. Break;
  36. Case 3:
  37. $Img = @ImageCreateFromPNG( $Image);
  38. Break;
  39. }
  40. //If the object is not created successfully, it means it is not an image file
  41. IF(Empty($Img)){
  42. //If there is an error when generating the thumbnail, you need to delete it Copied file
  43. IF($Type!=1){Unlink($Image);}
  44. Return False;
  45. }
  46. //If the resize operation is performed, then
  47. IF($Type==1){
  48. $w= ImagesX($Img);
  49. $h=ImagesY($Img);
  50. $width = $w;
  51. $height = $h;
  52. IF($width>$Dw){
  53. $Par=$Dw/$width;
  54. $width=$Dw;
  55. $height=$height*$Par;
  56. IF($height>$Dh){
  57. $Par=$Dh/$height;
  58. $height=$Dh;
  59. $width=$width *$Par;
  60. }
  61. }ElseIF($height>$Dh){
  62. $Par=$Dh/$height;
  63. $height=$Dh;
  64. $width=$width*$Par;
  65. IF($width> $Dw){
  66. $Par=$Dw/$width;
  67. $width=$Dw;
  68. $height=$height*$Par;
  69. }
  70. }Else{
  71. $width=$width;
  72. $height=$height ;
  73. }
  74. $nImg = ImageCreateTrueColor($width,$height); //Create a new true color canvas
  75. ImageCopyReSampled($nImg,$Img,0,0,0,0,$width,$height,$w,$ h);//Resample copy part of the image and resize it
  76. ImageJpeg ($nImg,$Image); //Output the image to the browser or file in JPEG format
  77. Return True;
  78. //If you are performing a thumbnail generation operation Then
  79. }Else{
  80. $w=ImagesX($Img);
  81. $h=ImagesY($Img);
  82. $width = $w;
  83. $height = $h;
  84. $nImg = ImageCreateTrueColor($Dw,$Dh );
  85. IF($h/$w>$Dh/$Dw){ //The height ratio is large
  86. $width=$Dw;
  87. $height=$h*$Dw/$w;
  88. $IntNH=$height- $Dh;
  89. ImageCopyReSampled($nImg, $Img, 0, -$IntNH/1.8, 0, 0, $Dw, $height, $w, $h);
  90. }Else{ //The width ratio is large
  91. $height= $Dh;
  92. $width=$w*$Dh/$h;
  93. $IntNW=$width-$Dw;
  94. ImageCopyReSampled($nImg, $Img, -$IntNW/1.8, 0, 0, 0, $width, $Dh, $w, $h);
  95. }
  96. ImageJpeg ($nImg,$Image);
  97. Return True;
  98. }
  99. }
  100. ?>
  101. < ;td>
  102. Upload pictures
  103. The file types allowed to be uploaded are:< ;/form>
  104. if($_SERVER['REQUEST_METHOD']=='POST'){
  105. if (!is_uploaded_file($_FILES["photo"][tmp_name])){
  106. echo "The picture is not Exists";
  107. exit();
  108. }
  109. if(!is_dir('img')){//If the path does not exist, create it
  110. mkdir('img');
  111. }
  112. $upfile=$_FILES["photo" ];
  113. $pinfo=pathinfo($upfile["name"]);
  114. $name=$pinfo['basename'];//File name
  115. $tmp_name=$upfile["tmp_name"];
  116. $file_type=$ pinfo['extension'];//Get the file type
  117. $showphpath=$path.$name;
  118. if(in_array($upfile["type"],$phtypes)){
  119. echo "The file type does not match! ";
  120. exit();
  121. }
  122. if(move_uploaded_file($tmp_name,$path.$name)){
  123. echo "Success! ";
  124. Img($showphpath,100,800,2);
  125. }
  126. echo "";
  127. }
  128. ?>
  129. < ;/html>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles