search
HomeBackend DevelopmentPHP TutorialHow to get remote image url and generate thumbnail in php

  1. /**

  2. *
  3. *Function: Adjust image size or generate thumbnail
  4. *Return: True/False
  5. *Parameters:
  6. * $Image The image that needs to be adjusted (including path)
  7. * $Dw=450 Maximum width when adjusting; when thumbnailing The absolute width
  8. * $Dh=450 The maximum height when adjusting; the absolute height when thumbnailing
  9. * $Type=1 1, adjust the size; 2, generate thumbnails
  10. */ bbs.it-home.org
  11. $phtypes=array('img/gif', 'img/jpg', 'img /jpeg', 'img/bmp', 'img/pjpeg', 'img/x-png');
  12. function compressImg($Image,$Dw,$Dh,$Type) {

  13. IF(!file_exists($Image)){
  14. return false;
  15. }
  16. // If you need to generate a thumbnail, copy the original image and reassign it to $Image (generate thumbnail operation)
  17. // When Type= =1, the original image file will not be copied, but the reduced image will be regenerated on the original image file (resize operation)
  18. IF($Type!=1){
  19. copy($Image,str_replace(" .","_x.",$Image));
  20. $Image=str_replace(".","_x.",$Image);
  21. }
  22. // Get the file type and create different objects according to different types
  23. $ImgInfo=getimagesize($Image);
  24. Switch($ImgInfo[2]){
  25. case 1:
  26. $Img =@imagecreatefromgif($Image);
  27. break;
  28. case 2:
  29. $Img =@imagecreatefromjpeg($ Image);
  30. Break;
  31. case 3:
  32. $Img =@imagecreatefrompng($Image);
  33. break;
  34. }
  35. // If the object is not created successfully, it means it is a non-image file
  36. IF(Empty($Img)){
  37. // If there is an error when generating thumbnails, you need to delete the copied files
  38. IF($Type!=1){
  39. unlink($Image);
  40. }
  41. return false;
  42. }
  43. // If yes To perform the resize operation,
  44. IF($Type==1){
  45. $w=ImagesX($Img);
  46. $h=ImagesY($Img);
  47. $width = $w;
  48. $height = $h;
  49. IF($width>$Dw){
  50. $Par=$Dw/$width;
  51. $width=$Dw;
  52. $height=$height*$Par;
  53. IF($height>$Dh){
  54. $Par= $Dh/$height;
  55. $height=$Dh;
  56. $width=$width*$Par;
  57. }
  58. } ElseIF($height>$Dh) {
  59. $Par=$Dh/$height;
  60. $height= $Dh;
  61. $width=$width*$Par;
  62. IF($width>$Dw){
  63. $Par=$Dw/$width;
  64. $width=$Dw;
  65. $height=$height*$Par;
  66. }
  67. } Else {
  68. $width=$width;
  69. $height=$height;
  70. }
  71. $nImg =ImageCreateTrueColor($width,$height);// Create a new true color canvas
  72. ImageCopyReSampled($nImg,$Img ,0,0,0,0,$width,$height,$w,$h);//Resample copy part of the image and resize it
  73. ImageJpeg($nImg,$Image);//Output the image in JPEG format To the browser or file
  74. return true;
  75. } Else {// If the thumbnail generation operation is performed,
  76. $w=ImagesX($Img);
  77. $h=ImagesY($Img);
  78. $width = $w;
  79. $height = $h;
  80. $nImg =ImageCreateTrueColor($Dw,$Dh);
  81. IF($h/$w>$Dh/$Dw){// Height is larger
  82. $width=$Dw;
  83. $ height=$h*$Dw/$w;
  84. $IntNH=$height-$Dh;
  85. ImageCopyReSampled($nImg, $Img, 0, -$IntNH/1.8, 0, 0, $Dw, $height, $w , $h);
  86. } Else {// Larger width ratio
  87. $height=$Dh;
  88. $width=$w*$Dh/$h;
  89. $IntNW=$width-$Dw;
  90. ImageCopyReSampled($nImg, $Img,-$IntNW/1.8,0,0,0, $width, $Dh, $w, $h);
  91. }
  92. ImageJpeg($nImg,$Image);
  93. return true;
  94. }
  95. };
  96. /**
  97. *Get the image on the server based on url
  98. *$url image path on the server $filename file name
  99. */
  100. function GrabImage($url,$filename="") {
  101. if($url=="") return false;
  102. if($filename=="") {
  103. $ext =strrchr($url,".");
  104. if($ext!=".gif" && $ext!=".jpg" && $ext!=".png")
  105. return false;
  106. $filename=date ("YmdHis").$ext;
  107. }
  108. ob_start();
  109. readfile($url);
  110. $img = ob_get_contents();
  111. ob_end_clean();
  112. $size = strlen($img);
  113. $fp2 =@fopen($filename, "a");
  114. fwrite($fp2,$img);
  115. fclose($fp2);
  116. return $filename;
  117. }
  118. ?>
Copy Code

Call method:

  1. //Network image path
  2. $imgPath = 'http://news.xxxx.cn/images/1382088444437.jpg';//Remote URL address
  3. $tempPath = 'aa/ bbs.jpg';//Save image path
  4. if(is_file($tempPath)){
  5. unlink($tempPath);
  6. }
  7. $bigImg=GrabImage($imgPath, $tempPath);
  8. compressImg($bigImg, 70,70,1);
  9. ?>
Copy code


Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor