SlideShare uma empresa Scribd logo
1 de 5
reating Thumbnails with PHP using the GD Library
By Angela Bradley, About.com Guide
See More About:
the gd library
graphics in php
php code examples

1 of 4

                                                                                                                      Previous Next
Before You Begin
When viewing files online, it is often necessary (or at least convenient) to be able to create a thumbnail image on the fly. You
may want to create previews of photos you are linking to, or perhaps resize photos for your website to a more user friendly size
without having to bother with a graphics program.


In this tutorial we will explore how to do this using imagecopyresized () and usingimagecopyresampled. We will also cover
calling the image from the PHP file, as well as saving the image to your server.


Before you begin, you should have a general knowledge of PHP and know a little about theGD Library. Also be sure you are
actually running the GD Library on your version of PHP.




Using Imagecopyresized ()
When using imagecopyresized () we have a number of parameters that need to be entered. They are: destination_image,
source_image, starting_X_ordinate, starting_Y_ordinate, initial_X_image_startpoint, initial_Y_image_startpoint, width, height,
original_width, original_height.


Here is an example of how to resize an image to a certain % of it's original size, and keep it proportional. Pay attention to the
comments in the code, as they explain what we are doing in each step.


          <?php
           // The file you are resizing
           $file = 'your.jpg';

           //This will set our output to 45% of the original size
           $size = 0.45;

           // This sets it to a .jpg, but you can change this to png or gif
          header('Content-type: image/jpeg');

           // Setting the resize parameters
           list($width, $height) = getimagesize($file);
           $modwidth = $width * $size;
           $modheight = $height * $size;

           // Creating the Canvas
           $tn= imagecreatetruecolor($modwidth, $modheight);
           $source = imagecreatefromjpeg($file);

           // Resizing our image to fit the canvas
          imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width,
          $height);

           // Outputs a jpg image, you could change this to gif or png if needed
          imagejpeg($tn);
           ?>
Using Imagecopyresampled ()
If you need a good quality reduction, and imagecopyresized () doesn't look nice enough, you may have better luck
with imagecopyresampled (). The parameters you need to define inimagecopyresampled () are: destination_image, source_image,
starting_X_ordinate, starting_Y_ordinate, initial_X_image_startpoint, initial_Y_image_startpoint, width, height, original_width,
original_height.


Here is an example of how to use imagecopyresampled (). If you are having trouble understanding, be sure to pay attention to the
comments in the code, they explain everything that is going on in each step.


         <?php
          // The file you are resizing
          $file = 'yourfile.jpg';

           //This will set our output to 45% of the original size
           $size = 0.45;

           // This sets it to a .jpg, but you can change this to png or gif
           header('Content-type: image/jpeg');

           // Setting the resize parameters
           list($width, $height) = getimagesize($file);
           $modwidth = $width * $size;
           $modheight = $height * $size;

          // Resizing the Image
          $tn = imagecreatetruecolor($modwidth, $modheight);
          $image = imagecreatefromjpeg($file);
         imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width,
         $height);

          // Outputting a .jpg, you can make this gif or png if you want
          //notice we set the quality (third value) to 100
         imagejpeg($tn, null, 100);
          ?>

Using The Thumbnail Images
To use your thumbnail images you have two options: you can call the .php file directly, or you can save the new image you
created.
If you are using the .php file directly, you must be sure that nothing else is sent to the browser from the PHP file (text for
example), that would keep it from being read as an image. You can link it the same way you would link any other graphic:
          <imgsrc="http://www.my_site.com/my_thumbnail_program.php">
You can also save the image through the imagejpeg () function (or gif or png.) Below is an example of how you would do this:
          <?php


          //Name you want to save your file as


         $save = 'myfile.jpg';


          $file = 'original.jpg';
         echo "Creating file: $save";
          $size = 0.45;
          header('Content-type: image/jpeg') ;
          list($width, $height) = getimagesize($file) ;
          $modwidth = $width * $size;
          $modheight = $height * $size;
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width,
         $height) ;

            // Here we are saving the .jpg, you can make this gif or png if you want
            //the file name is set above, and the quality is set to 100%
           imagejpeg($tn, $save, 100) ;
            ?>
This code saves the thumbnailed file onto your server as whatever you specified($save). You can then call this new graphic file
directly, and do not need the PHP again once the image file has been created.




PHP Thumbnail Image creation script
Creating thumbnail images is a very common requirement. Many scripts use this to create thumbnails of uploaded

images or any stored images. We will learn how to create thumbnail images while uploading images to the server.

Please read the tutorials on file upload when register_global is off to know how to upload files to the server with

necessary                                permissions                             in                           PHP                          5.



The file ( or image ) will be first uploaded to a directory and then one thumbnail image will be created in a

different directory. So for creating the thumbnail we will check the file extension ( it is gif or jpeg image ) but to

keep the script simple we are not checking here the file size. So if the file size is to be restricted then file size

validation is to        be     added. You can see            how the file       size   checking is done         in file    upload tutorial.



This script is tested with PHP 5.2.6 with register_global is OFF. Please update your script if you have downloaded

the old version of this.


<FORM                  ENCTYPE="multipart/form-data"                         ACTION="addimgck.php"                         METHOD=POST>
Upload                  this                 file:                <INPUT                    NAME="userfile"                       TYPE="file">
<INPUT TYPE="submit" VALUE="Send File"></FORM>


We will now see the addimgck.php file and check the code to create the thumbnail image. We will upload the file

to the upimg directory and check to see if file upload is successful or not.


// Below lines are to display file name, temp name and file type , you can use them for testing your script

only//////

echo                             "File                           Name:                              ".$_FILES[userfile][name]."<br>";

echo                           "tmp                          name:                            ".$_FILES[userfile][tmp_name]."<br>";

echo                             "File                             Type:                              ".$_FILES[userfile][type]."<br>";
echo                                                                                                                              "<br><br>";
///////////////////////////////////////////////////////////////////////////

$add="upimg/".$_FILES[userfile][name]; // the path with the file name where the file will be stored, upload is the

directory                                                                                                                                   name.

//echo                                                                                                                                       $add;

if(move_uploaded_file                                                                                 ($_FILES[userfile][tmp_name],$add)){

echo                        "Successfully                                     uploaded                           the                        mage";

chmod("$add",0777);



}else{echo       "Failed             to     upload          file        Contact       Site        admin        to      fix     the       problem";
exit;}


Now the image is uploaded to the directory and from that image we will create thumbnail image of it. We will first

set the height and width of the thumbnail images to be generated. Then we will check the type of the file and

now we are checking for file type of gif and jpeg and if the image is not of this type then we are terminating the

script giving an error message.


/////////                       Start                            the                     thumbnail                      generation//////////////

$n_width=100;              //             Fix         the               width         of          the          thumb           nail         images

$n_height=100;             //             Fix             the           height           of       the           thumb           nail        imaage



$tsrc="thimg/".$_FILES[userfile][name];                         //     Path      where        thumb     nail        image     will     be   stored

//echo                                                                                                                                       $tsrc;

if (!($_FILES[userfile][type] =="image/pjpeg" OR $_FILES[userfile][type]=="image/gif")){echo "Your uploaded

file     must      be           of        JPG        or          GIF.         Other      file     types        are      not          allowed<BR>";
exit;}


Now let us start with gif file thumb nail image creation. We will first read the height and width of the uploaded

image and then resize it to our thumbnail image size. Note that in some GD library support GIF version is not

included so to check that we have used one if condition and accordingly used jpeg support. We will be using

imagecreatetruecolor to retain the actual color combination of the main picture.


////////////            Starting                     of                 GIF               thumb                nail            creation///////////

if                                                                                                (@$_FILES[userfile][type]=="image/gif")

{

$im=ImageCreateFromGIF($add);
$width=ImageSx($im);                        //                   Original             picture             width                is           stored

$height=ImageSy($im);                           //               Original             picture             height               is           stored
$newimage=imagecreatetruecolor($n_width,$n_height);

imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);

if                                                (function_exists("imagegif"))                                                {

Header("Content-type:                                                                                               image/gif");

ImageGIF($newimage,$tsrc);

}

elseif                                             (function_exists("imagejpeg"))                                              {

Header("Content-type:                                                                                             image/jpeg");

ImageJPEG($newimage,$tsrc);

}

chmod("$tsrc",0777);

}//////////           end           of             gif          file          thumb          nail              creation//////////



//////////////          starting             of               JPG           thumb            nail              creation//////////

if($_FILES[userfile][type]=="image/pjpeg"){

$im=ImageCreateFromJPEG($add);

$width=ImageSx($im);                //              Original             picture          width            is             stored

$height=ImageSy($im);                //              Original            picture          height           is             stored

$newimage=imagecreatetruecolor($n_width,$n_height);

imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);

ImageJpeg($newimage,$tsrc);

chmod("$tsrc",0777);

}
//////////////// End of JPG thumb nail creation //////////




Same      way    we     can   add        other     graphics     format     like    BMP,   PNG       etc   to     the    system



Download the ZIP file here thumbnail.zip

Mais conteúdo relacionado

Último

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Último (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Reating thumbnails with php using the gd library

  • 1. reating Thumbnails with PHP using the GD Library By Angela Bradley, About.com Guide See More About: the gd library graphics in php php code examples 1 of 4 Previous Next Before You Begin When viewing files online, it is often necessary (or at least convenient) to be able to create a thumbnail image on the fly. You may want to create previews of photos you are linking to, or perhaps resize photos for your website to a more user friendly size without having to bother with a graphics program. In this tutorial we will explore how to do this using imagecopyresized () and usingimagecopyresampled. We will also cover calling the image from the PHP file, as well as saving the image to your server. Before you begin, you should have a general knowledge of PHP and know a little about theGD Library. Also be sure you are actually running the GD Library on your version of PHP. Using Imagecopyresized () When using imagecopyresized () we have a number of parameters that need to be entered. They are: destination_image, source_image, starting_X_ordinate, starting_Y_ordinate, initial_X_image_startpoint, initial_Y_image_startpoint, width, height, original_width, original_height. Here is an example of how to resize an image to a certain % of it's original size, and keep it proportional. Pay attention to the comments in the code, as they explain what we are doing in each step. <?php // The file you are resizing $file = 'your.jpg'; //This will set our output to 45% of the original size $size = 0.45; // This sets it to a .jpg, but you can change this to png or gif header('Content-type: image/jpeg'); // Setting the resize parameters list($width, $height) = getimagesize($file); $modwidth = $width * $size; $modheight = $height * $size; // Creating the Canvas $tn= imagecreatetruecolor($modwidth, $modheight); $source = imagecreatefromjpeg($file); // Resizing our image to fit the canvas imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); // Outputs a jpg image, you could change this to gif or png if needed imagejpeg($tn); ?>
  • 2. Using Imagecopyresampled () If you need a good quality reduction, and imagecopyresized () doesn't look nice enough, you may have better luck with imagecopyresampled (). The parameters you need to define inimagecopyresampled () are: destination_image, source_image, starting_X_ordinate, starting_Y_ordinate, initial_X_image_startpoint, initial_Y_image_startpoint, width, height, original_width, original_height. Here is an example of how to use imagecopyresampled (). If you are having trouble understanding, be sure to pay attention to the comments in the code, they explain everything that is going on in each step. <?php // The file you are resizing $file = 'yourfile.jpg'; //This will set our output to 45% of the original size $size = 0.45; // This sets it to a .jpg, but you can change this to png or gif header('Content-type: image/jpeg'); // Setting the resize parameters list($width, $height) = getimagesize($file); $modwidth = $width * $size; $modheight = $height * $size; // Resizing the Image $tn = imagecreatetruecolor($modwidth, $modheight); $image = imagecreatefromjpeg($file); imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); // Outputting a .jpg, you can make this gif or png if you want //notice we set the quality (third value) to 100 imagejpeg($tn, null, 100); ?> Using The Thumbnail Images To use your thumbnail images you have two options: you can call the .php file directly, or you can save the new image you created. If you are using the .php file directly, you must be sure that nothing else is sent to the browser from the PHP file (text for example), that would keep it from being read as an image. You can link it the same way you would link any other graphic: <imgsrc="http://www.my_site.com/my_thumbnail_program.php"> You can also save the image through the imagejpeg () function (or gif or png.) Below is an example of how you would do this: <?php //Name you want to save your file as $save = 'myfile.jpg'; $file = 'original.jpg'; echo "Creating file: $save"; $size = 0.45; header('Content-type: image/jpeg') ; list($width, $height) = getimagesize($file) ; $modwidth = $width * $size; $modheight = $height * $size; $tn = imagecreatetruecolor($modwidth, $modheight) ; $image = imagecreatefromjpeg($file) ;
  • 3. imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; // Here we are saving the .jpg, you can make this gif or png if you want //the file name is set above, and the quality is set to 100% imagejpeg($tn, $save, 100) ; ?> This code saves the thumbnailed file onto your server as whatever you specified($save). You can then call this new graphic file directly, and do not need the PHP again once the image file has been created. PHP Thumbnail Image creation script Creating thumbnail images is a very common requirement. Many scripts use this to create thumbnails of uploaded images or any stored images. We will learn how to create thumbnail images while uploading images to the server. Please read the tutorials on file upload when register_global is off to know how to upload files to the server with necessary permissions in PHP 5. The file ( or image ) will be first uploaded to a directory and then one thumbnail image will be created in a different directory. So for creating the thumbnail we will check the file extension ( it is gif or jpeg image ) but to keep the script simple we are not checking here the file size. So if the file size is to be restricted then file size validation is to be added. You can see how the file size checking is done in file upload tutorial. This script is tested with PHP 5.2.6 with register_global is OFF. Please update your script if you have downloaded the old version of this. <FORM ENCTYPE="multipart/form-data" ACTION="addimgck.php" METHOD=POST> Upload this file: <INPUT NAME="userfile" TYPE="file"> <INPUT TYPE="submit" VALUE="Send File"></FORM> We will now see the addimgck.php file and check the code to create the thumbnail image. We will upload the file to the upimg directory and check to see if file upload is successful or not. // Below lines are to display file name, temp name and file type , you can use them for testing your script only////// echo "File Name: ".$_FILES[userfile][name]."<br>"; echo "tmp name: ".$_FILES[userfile][tmp_name]."<br>"; echo "File Type: ".$_FILES[userfile][type]."<br>"; echo "<br><br>";
  • 4. /////////////////////////////////////////////////////////////////////////// $add="upimg/".$_FILES[userfile][name]; // the path with the file name where the file will be stored, upload is the directory name. //echo $add; if(move_uploaded_file ($_FILES[userfile][tmp_name],$add)){ echo "Successfully uploaded the mage"; chmod("$add",0777); }else{echo "Failed to upload file Contact Site admin to fix the problem"; exit;} Now the image is uploaded to the directory and from that image we will create thumbnail image of it. We will first set the height and width of the thumbnail images to be generated. Then we will check the type of the file and now we are checking for file type of gif and jpeg and if the image is not of this type then we are terminating the script giving an error message. ///////// Start the thumbnail generation////////////// $n_width=100; // Fix the width of the thumb nail images $n_height=100; // Fix the height of the thumb nail imaage $tsrc="thimg/".$_FILES[userfile][name]; // Path where thumb nail image will be stored //echo $tsrc; if (!($_FILES[userfile][type] =="image/pjpeg" OR $_FILES[userfile][type]=="image/gif")){echo "Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>"; exit;} Now let us start with gif file thumb nail image creation. We will first read the height and width of the uploaded image and then resize it to our thumbnail image size. Note that in some GD library support GIF version is not included so to check that we have used one if condition and accordingly used jpeg support. We will be using imagecreatetruecolor to retain the actual color combination of the main picture. //////////// Starting of GIF thumb nail creation/////////// if (@$_FILES[userfile][type]=="image/gif") { $im=ImageCreateFromGIF($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored
  • 5. $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); if (function_exists("imagegif")) { Header("Content-type: image/gif"); ImageGIF($newimage,$tsrc); } elseif (function_exists("imagejpeg")) { Header("Content-type: image/jpeg"); ImageJPEG($newimage,$tsrc); } chmod("$tsrc",0777); }////////// end of gif file thumb nail creation////////// ////////////// starting of JPG thumb nail creation////////// if($_FILES[userfile][type]=="image/pjpeg"){ $im=ImageCreateFromJPEG($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); ImageJpeg($newimage,$tsrc); chmod("$tsrc",0777); } //////////////// End of JPG thumb nail creation ////////// Same way we can add other graphics format like BMP, PNG etc to the system Download the ZIP file here thumbnail.zip