PHP function for downloading images from http

This function will download images from another site , resize them and put suffix (if needed).

function download_resized_jpeg($filename,$width,$height,$suffix){
	$name = explode('/',$filename);
	$newfilename = end($name);

	// Content type
	//header('Content-Type: image/jpeg');

	list($width_orig, $height_orig, $type) = getimagesize($filename);

	$ratio_orig = $width_orig/$height_orig;

	if ($width/$height > $ratio_orig) {
	   $width = $height*$ratio_orig;
	} else {
	   $height = $width/$ratio_orig;
	}

	// Resample
	$image_p = imagecreatetruecolor($width, $height);
	if ($type == 1)
    {
        $image = imagecreatefromgif($filename);
    }
    elseif ($type == 2)
    {
        $image = imagecreatefromjpeg($filename);
    }
    elseif ($type == 3)
    {
        $image = imagecreatefrompng($filename);
    }
    else
    {
        $image = imagecreatefromwbmp($filename);
    }
	
	if($type==1 or $type==3) //this code below should preserve transparency but I couldn't try it out for now...
    {
        imagealphablending($image_p, false);
        imagesavealpha($image_p, true);
        imagecolortransparent($image_p, imagecolorallocatealpha($image_p, 0, 0, 0, 127));
    }
	
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

	// Output
	if ($type == 1)
        imagegif ($image_p, "../pictures/$newfilename$suffix".".gif", 100);
    elseif ($type == 2)
        imagejpeg($image_p, "../pictures/$newfilename$suffix".".jpg", 100);
    elseif ($type == 3)
        imagepng ($image_p, "../pictures/$newfilename$suffix".".png", 0);
    else
        imagewbmp ($image_p, "../pictures/$newfilename$suffix".".bmp", 100);
}

Leave a Reply

Your email address will not be published. Required fields are marked *