<?
function create_preview_from_resource($imgc, $w, $h) {
	if (!is_resource($imgc) || $w == 0 || $h == 0)
		return false;
	$img_x=imagesx($imgc);
	$img_y=imagesy($imgc);
	if ($img_x==$img_y) {
		$dstW=$w;
		$dstH=$h;
	} elseif ($img_x>$img_y) {
		$prop=$img_x/$img_y;
		$dstW=$w;
		$dstH=ceil($dstW/$prop);
	} else {
		$prop=$img_y/$img_x;
		$dstH=$h;
		$dstW=ceil($dstH/$prop);
	}
	$screen=imagecreatetruecolor($dstW, $dstH);
	imagecopyresampled($screen, $imgc, 0, 0, 0, 0, $dstW, $dstH, $img_x, $img_y);
	return $screen;
}

function create_preview($filePath, $savePath, $w = 0, $h = 0) {
	if (!is_file($filePath) || $w == 0 || $h == 0)
		return false;
	if ($imgc = @imagecreatefromstring(file_get_contents($filePath))) {
		$screen = create_preview_from_resource($imgc, $w, $h);
		imagedestroy($imgc);
		if (!imagepng($screen, $savePath)) {
			imagedestroy($screen);
			return false;
		}
		imagedestroy($screen);
		return true;
	}
	if (class_exists('ffmpeg_movie') && @$movie = new ffmpeg_movie($filePath)) {
		$frame_number = rand(1, $movie -> getFrameCount());
		$videPreviewFrameNum = $frame_number;
		$frame = $movie -> getFrame($frame_number);
		if (!$frame)
			return false;
		$imgc = $frame -> toGDImage();
		$screen = create_preview_from_resource($imgc, $w, $h);
		imagedestroy($imgc);
		if (!imagepng($screen, $savePath)) {
			imagedestroy($screen);
			return false;
		}
		imagedestroy($screen);
		return true;
	}
	return false;
}
?>