<?php
$frame_bg = 'frame_bg.png';
$default_photo='frame_default.jpg';

//Custom image in frame
$imglist=array();
$img_folder = "../photos/";
$imgs = dir($img_folder);

while ($file = $imgs->read()) {
	$tmp_extension = strtoupper(substr($file, -3));
   if($tmp_extension=="JPG")
     		$imglist[]= "$file";
} 
closedir($imgs->handle);

if(count($imglist)>0){
	//generate a random image from list
	shuffle($imglist);
	$image=$imglist[0];
	$pic = imagecreatefromjpeg("{$img_folder}{$image}");
}else{
	$pic = imagecreatefromjpeg($default_photo);
}	
	
	$new_w=180; //170
	$new_h=145; //190

	$photoframe=imagecreatetruecolor(180,145);	
	$newimg=imagecreatetruecolor($new_w,$new_h);
	$frame=imagecreatefrompng($frame_bg);

	$org_w= imagesX($pic);
	$org_h= imagesY($pic);

	$CropW=0;$CropW2=0;$CropH=0;$CropH2=0;

	$RatioW=$new_w/$org_w;
	$RatioH=$new_h/$org_h;
	If($RatioW>$RatioH){
		$CropH=ceil((($org_h*$RatioW)-$new_h)/2);
		$CropH2=ceil(($org_h*$RatioW)-$new_h);
	}else{
		$CropW=ceil((($org_w*$RatioH)-$new_w)/2);
		$CropW2=ceil(($org_w*$RatioH)-$new_w);
	}
	imagecopyresampled($newimg, $pic, 0,0,$CropW,$CropH, $new_w, $new_h, $org_w-$CropW2, $org_h-$CropH2);
	//$newimg = imagerotate($newimg, -4, 0);
	imagecopyresampled($photoframe,$newimg,0,0,0,0,180,145,180,145);
	imagecopyresampled($photoframe,$frame,0,0,0,0,180,145,180,145);

header('Content-type: image/jpeg');
header("Cache-Control: no-cache, must-revalidate");
imagejpeg($photoframe,'',90);
exit;
?>