How to copy and resize image using php

In this tutorial we are showing how to create new copy and resized existing images. Are you looking for image upload, create copy and Resize PHP script. This is for you, It is very simple PHP script to re-sizing image into different dimensions. It’s very useful to your web projects to save hosting space and bandwidth to reduce the original image to compressed size.

PHP Code For Create New Copy and Resize Existing Images

<?php
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 300);
$srcPath = 'images/';

$srcDir = opendir($srcPath);
while($readFile = readdir($srcDir))
{
    if($readFile != '.' && $readFile != '..')
    {
        $MyFile="thunmb_".$readFile;
        if (!file_exists($MyFile)) 
        {
            $filename="images/".$readFile;
            $Newfilename="images/thunmb_".$readFile;
            
            $source         = $filename;
            $destination    = $Newfilename;
            $maxsize        = 100;
            resize_image($source, $destination, $maxsize);
        }
    }
}
closedir($srcDir);

function resize_image($source, $destination, $maxsize)
{
    $size = getimagesize($source);
    $width_orig = $size[0];
    $height_orig = $size[1];
    unset($size);
    $height = $maxsize+1;
    $width = $maxsize;
    while($height > $maxsize){
        $height = round($width*$height_orig/$width_orig);
        $width = ($height > $maxsize)?--$width:$width;
    }
    unset($width_orig,$height_orig,$maxsize);
    $images_orig    = imagecreatefromstring( file_get_contents($source) );
    $photoX         = imagesx($images_orig);
    $photoY         = imagesy($images_orig);
    $images_fin     = imagecreatetruecolor($width,$height);
    imagesavealpha($images_fin,true);
    $trans_colour   = imagecolorallocatealpha($images_fin,0,0,0,127);
    imagefill($images_fin,0,0,$trans_colour);
    unset($trans_colour);
    ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
    unset($photoX,$photoY,$width,$height);
    imagepng($images_fin,$destination);
    unset($destination);
    ImageDestroy($images_orig);
    ImageDestroy($images_fin);
}
?>

Leave a Reply

Related Posts: You may like

Extract Total Number of Image And Missing Alt Attribute using php

How to extract Heading tags using PHP from string

How to remove whitespace from string using php

Remove All Special Characters From String PHP

PHPKIDA Offering Free Tools:

INSTA DOWNLOADER

Download Instagram Videos & Photos.

Download Now

CURRENCY CONVERTER

Real Time Currency Converter

Convert Now

ROBOST.TXT GEN.

Robots.txt File Creater

Create Now

HTML MINIFIER

Compress yout HTML Code

Minify Now

CSS MINIFIER

Compress yout CSS Code

Minify Now

JAVASCRIPT MINIFIER

Compress yout JavaScript Code

Minify Now

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.