1
0
mirror of https://github.com/mosbth/cimage.git synced 2025-08-09 09:36:38 +02:00

update docs/api with phpdoc

This commit is contained in:
Mikael Roos
2015-12-02 11:05:41 +01:00
parent 91ae49b3f3
commit b871dd7f1c
36 changed files with 4492 additions and 1490 deletions

View File

@@ -0,0 +1,257 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<meta charset="utf-8"/>
<title>CImage API Documentaion</title>
<meta name="author" content=""/>
<meta name="description" content=""/>
<link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="../css/font-awesome.min.css" rel="stylesheet">
<link href="../css/prism.css" rel="stylesheet" media="all"/>
<link href="../css/template.css" rel="stylesheet" media="all"/>
<!--[if lt IE 9]>
<script src="../js/html5.js"></script>
<![endif]-->
<script src="../js/jquery-1.11.0.min.js"></script>
<script src="../js/ui/1.10.4/jquery-ui.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery.smooth-scroll.js"></script>
<script src="../js/prism.min.js"></script>
<!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit-->
<script type="text/javascript">
function loadExternalCodeSnippets() {
Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function (pre) {
var src = pre.getAttribute('data-src');
var extension = (src.match(/\.(\w+)$/) || [, ''])[1];
var language = 'php';
var code = document.createElement('code');
code.className = 'language-' + language;
pre.textContent = '';
code.textContent = 'Loading…';
pre.appendChild(code);
var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status < 400 && xhr.responseText) {
code.textContent = xhr.responseText;
Prism.highlightElement(code);
}
else if (xhr.status >= 400) {
code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
}
else {
code.textContent = '✖ Error: File does not exist or is empty';
}
}
};
xhr.send(null);
});
}
$(document).ready(function(){
loadExternalCodeSnippets();
});
$('#source-view').on('shown', function () {
loadExternalCodeSnippets();
})
</script>
<link rel="shortcut icon" href="../images/favicon.ico"/>
<link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
<link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
<link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="icon-ellipsis-vertical"></i>
</a>
<a class="brand" href="../index.html">CImage API Documentaion</a>
<div class="nav-collapse">
<ul class="nav pull-right">
<li class="dropdown" id="charts-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../graphs/class.html">
<i class="icon-list-alt"></i>&#160;Class hierarchy diagram
</a>
</li>
</ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
<a href="../reports/deprecated.html">
<i class="icon-list-alt"></i>&#160;Deprecated <span class="label label-info pull-right">0</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<!--<div class="go_to_top">-->
<!--<a href="#___" style="color: inherit">Back to top&#160;&#160;<i class="icon-upload icon-white"></i></a>-->
<!--</div>-->
</div>
<div id="___" class="container-fluid">
<section class="row-fluid">
<div class="span2 sidebar">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-306826089"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-306826089" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="row-fluid">
<div class="span10 offset2">
<div class="row-fluid">
<div class="span8 content file">
<nav>
</nav>
<a href="#source-view" role="button" class="pull-right btn" data-toggle="modal"><i class="icon-code"></i></a>
<h1><small></small>CAsciiArt.php</h1>
<p><em></em></p>
<h2>Classes</h2>
<table class="table table-hover">
<tr>
<td><a href="../classes/CAsciiArt.html">CAsciiArt</a></td>
<td><em>Create an ASCII version of an image.</em></td>
</tr>
</table>
</div>
<aside class="span4 detailsbar">
<dl>
<dt>Package</dt>
<dd><div class="namespace-wrapper">\Default</div></dd>
</dl>
<h2>Tags</h2>
<table class="table table-condensed">
<tr><td colspan="2"><em>None found</em></td></tr>
</table>
</aside>
</div>
</div>
</section>
<div id="source-view" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="source-view-label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="source-view-label"></h3>
</div>
<div class="modal-body">
<pre data-src="../files/CAsciiArt.php.txt" class="language-php line-numbers"></pre>
</div>
</div>
<footer class="row-fluid">
<section class="span10 offset2">
<section class="row-fluid">
<section class="span10 offset1">
<section class="row-fluid footer-sections">
<section class="span4">
<h1><i class="icon-code"></i></h1>
<div>
<ul>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-bar-chart"></i></h1>
<div>
<ul>
<li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-pushpin"></i></h1>
<div>
<ul>
<li><a href="../reports/errors.html">Errors</a></li>
<li><a href="../reports/markers.html">Markers</a></li>
</ul>
</div>
</section>
</section>
</section>
</section>
<section class="row-fluid">
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>
</footer>
</div>
</body>
</html>

View File

@@ -0,0 +1,213 @@
<?php
/**
* Create an ASCII version of an image.
*
*/
class CAsciiArt
{
/**
* Character set to use.
*/
private $characterSet = array(
'one' => "#0XT|:,.' ",
'two' => "@%#*+=-:. ",
'three' => "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
);
/**
* Current character set.
*/
private $characters = null;
/**
* Length of current character set.
*/
private $charCount = null;
/**
* Scale of the area to swap to a character.
*/
private $scale = null;
/**
* Strategy to calculate luminance.
*/
private $luminanceStrategy = null;
/**
* Constructor which sets default options.
*/
public function __construct()
{
$this->setOptions();
}
/**
* Add a custom character set.
*
* @param string $key for the character set.
* @param string $value for the character set.
*
* @return $this
*/
public function addCharacterSet($key, $value)
{
$this->characterSet[$key] = $value;
return $this;
}
/**
* Set options for processing, defaults are available.
*
* @param array $options to use as default settings.
*
* @return $this
*/
public function setOptions($options = array())
{
$default = array(
"characterSet" => 'two',
"scale" => 14,
"luminanceStrategy" => 3,
"customCharacterSet" => null,
);
$default = array_merge($default, $options);
if (!is_null($default['customCharacterSet'])) {
$this->addCharacterSet('custom', $default['customCharacterSet']);
$default['characterSet'] = 'custom';
}
$this->scale = $default['scale'];
$this->characters = $this->characterSet[$default['characterSet']];
$this->charCount = strlen($this->characters);
$this->luminanceStrategy = $default['luminanceStrategy'];
return $this;
}
/**
* Create an Ascii image from an image file.
*
* @param string $filename of the image to use.
*
* @return string $ascii with the ASCII image.
*/
public function createFromFile($filename)
{
$img = imagecreatefromstring(file_get_contents($filename));
list($width, $height) = getimagesize($filename);
$ascii = null;
$incY = $this->scale;
$incX = $this->scale / 2;
for ($y = 0; $y < $height - 1; $y += $incY) {
for ($x = 0; $x < $width - 1; $x += $incX) {
$toX = min($x + $this->scale / 2, $width - 1);
$toY = min($y + $this->scale, $height - 1);
$luminance = $this->luminanceAreaAverage($img, $x, $y, $toX, $toY);
$ascii .= $this->luminance2character($luminance);
}
$ascii .= PHP_EOL;
}
return $ascii;
}
/**
* Get the luminance from a region of an image using average color value.
*
* @param string $img the image.
* @param integer $x1 the area to get pixels from.
* @param integer $y1 the area to get pixels from.
* @param integer $x2 the area to get pixels from.
* @param integer $y2 the area to get pixels from.
*
* @return integer $luminance with a value between 0 and 100.
*/
public function luminanceAreaAverage($img, $x1, $y1, $x2, $y2)
{
$numPixels = ($x2 - $x1 + 1) * ($y2 - $y1 + 1);
$luminance = 0;
for ($x = $x1; $x <= $x2; $x++) {
for ($y = $y1; $y <= $y2; $y++) {
$rgb = imagecolorat($img, $x, $y);
$red = (($rgb >> 16) & 0xFF);
$green = (($rgb >> 8) & 0xFF);
$blue = ($rgb & 0xFF);
$luminance += $this->getLuminance($red, $green, $blue);
}
}
return $luminance / $numPixels;
}
/**
* Calculate luminance value with different strategies.
*
* @param integer $red The color red.
* @param integer $green The color green.
* @param integer $blue The color blue.
*
* @return float $luminance with a value between 0 and 1.
*/
public function getLuminance($red, $green, $blue)
{
switch($this->luminanceStrategy) {
case 1:
$luminance = ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255;
break;
case 2:
$luminance = ($red * 0.299 + $green * 0.587 + $blue * 0.114) / 255;
break;
case 3:
$luminance = sqrt(0.299 * pow($red, 2) + 0.587 * pow($green, 2) + 0.114 * pow($blue, 2)) / 255;
break;
case 0:
default:
$luminance = ($red + $green + $blue) / (255 * 3);
}
return $luminance;
}
/**
* Translate the luminance value to a character.
*
* @param string $position a value between 0-100 representing the
* luminance.
*
* @return string with the ascii character.
*/
public function luminance2character($luminance)
{
$position = (int) round($luminance * ($this->charCount - 1));
$char = $this->characters[$position];
return $char;
}
}

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-785926434"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1589006485"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-785926434" class="accordion-body collapse in">
<div id="namespace-1589006485" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -245,7 +246,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -21,6 +21,33 @@ class CHttpGet
/**
* Build an encoded url.
*
* @param string $baseUrl This is the original url which will be merged.
* @param string $merge Thse parts should be merged into the baseUrl,
* the format is as parse_url.
*
* @return string $url as the modified url.
*/
public function buildUrl($baseUrl, $merge)
{
$parts = parse_url($baseUrl);
$parts = array_merge($parts, $merge);
$url = $parts['scheme'];
$url .= "://";
$url .= $parts['host'];
$url .= isset($parts['port'])
? ":" . $parts['port']
: "" ;
$url .= $parts['path'];
return $url;
}
/**
* Set the url for the request.
*
@@ -30,6 +57,18 @@ class CHttpGet
*/
public function setUrl($url)
{
$parts = parse_url($url);
$path = "";
if (isset($parts['path'])) {
$pathParts = explode('/', $parts['path']);
unset($pathParts[0]);
foreach ($pathParts as $value) {
$path .= "/" . rawurlencode($value);
}
}
$url = $this->buildUrl($url, array("path" => $path));
$this->request['url'] = $url;
return $this;
}
@@ -62,7 +101,14 @@ class CHttpGet
*/
public function parseHeader()
{
$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
//$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
$rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
# Handle multiple responses e.g. with redirections (proxies too)
$headerGroups = explode("\r\n\r\n", $rawHeaders);
# We're only interested in the last one
$header = explode("\r\n", end($headerGroups));
$output = array();
if ('HTTP' === substr($header[0], 0, 4)) {
@@ -86,6 +132,8 @@ class CHttpGet
*
* @param boolean $debug set to true to dump headers.
*
* @throws Exception when curl fails to retrieve url.
*
* @return boolean
*/
public function doGet($debug = false)
@@ -99,6 +147,8 @@ class CHttpGet
CURLINFO_HEADER_OUT => $debug,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 5,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 2,
);
$ch = curl_init();
@@ -106,7 +156,7 @@ class CHttpGet
$response = curl_exec($ch);
if (!$response) {
return false;
throw new Exception("Failed retrieving url, details follows: " . curl_error($ch));
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-163130442"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1494355388"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-163130442" class="accordion-body collapse in">
<div id="namespace-1494355388" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -245,7 +246,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -63,6 +63,13 @@ class CImage
/**
* Add HTTP headers for outputing image.
*/
private $HTTPHeader = array();
/**
* Default background color, red, green, blue, alpha.
*
@@ -113,13 +120,6 @@ class CImage
/**
* The root folder of images (only used in constructor to create $pathToImage?).
*/
private $imageFolder;
/**
* Image filename, may include subdirectory, relative from $imageFolder
*/
@@ -193,6 +193,7 @@ class CImage
* Path to command for filter optimize, for example optipng or null.
*/
private $pngFilter;
private $pngFilterCmd;
@@ -200,13 +201,16 @@ class CImage
* Path to command for deflate optimize, for example pngout or null.
*/
private $pngDeflate;
private $pngDeflateCmd;
/**
* Path to command to optimize jpeg images, for example jpegtran or null.
*/
private $jpegOptimize;
private $jpegOptimize;
private $jpegOptimizeCmd;
/**
@@ -282,6 +286,56 @@ class CImage
private $fillToFit;
/**
* To store value for option scale.
*/
private $scale;
/**
* To store value for option.
*/
private $rotateBefore;
/**
* To store value for option.
*/
private $rotateAfter;
/**
* To store value for option.
*/
private $autoRotate;
/**
* To store value for option.
*/
private $sharpen;
/**
* To store value for option.
*/
private $emboss;
/**
* To store value for option.
*/
private $blur;
/**
* Used with option area to set which parts of the image to use.
*/
@@ -318,6 +372,38 @@ class CImage
private $useCache = true;
/*
* Set whitelist for valid hostnames from where remote source can be
* downloaded.
*/
private $remoteHostWhitelist = null;
/*
* Do verbose logging to file by setting this to a filename.
*/
private $verboseFileName = null;
/*
* Output to ascii can take som options as an array.
*/
private $asciiOptions = array();
/*
* Image copy strategy, defaults to RESAMPLE.
*/
const RESIZE = 1;
const RESAMPLE = 2;
private $copyStrategy = NULL;
/**
* Properties, the class is mutable and the method setOptions()
* decides (partly) what properties are created.
@@ -332,9 +418,7 @@ class CImage
public $crop_x;
public $crop_y;
public $filters;
private $type; // Calculated from source image
private $attr; // Calculated from source image
private $useOriginal; // Use original image if possible
@@ -391,9 +475,7 @@ class CImage
/**
* Use cache or not.
*
* @todo clean up how $this->noCache is used in other methods.
*
* @param string $use true or false to use cache.
* @param boolean $use true or false to use cache.
*
* @return $this
*/
@@ -405,6 +487,27 @@ class CImage
/**
* Create and save a dummy image. Use dimensions as stated in
* $this->newWidth, or $width or default to 100 (same for height.
*
* @param integer $width use specified width for image dimension.
* @param integer $height use specified width for image dimension.
*
* @return $this
*/
public function createDummyImage($width = null, $height = null)
{
$this->newWidth = $this->newWidth ?: $width ?: 100;
$this->newHeight = $this->newHeight ?: $height ?: 100;
$this->image = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
return $this;
}
/**
* Allow or disallow remote image download.
*
@@ -418,10 +521,12 @@ class CImage
$this->allowRemote = $allow;
$this->remotePattern = is_null($pattern) ? $this->remotePattern : $pattern;
$this->log("Set remote download to: "
$this->log(
"Set remote download to: "
. ($this->allowRemote ? "true" : "false")
. " using pattern "
. $this->remotePattern);
. $this->remotePattern
);
return $this;
}
@@ -445,7 +550,7 @@ class CImage
/**
* Set whitelist for valid hostnames from where remote source can be
* Set whitelist for valid hostnames from where remote source can be
* downloaded.
*
* @param array $whitelist with regexp hostnames to allow download from.
@@ -455,14 +560,17 @@ class CImage
public function setRemoteHostWhitelist($whitelist = null)
{
$this->remoteHostWhitelist = $whitelist;
$this->log("Setting remote host whitelist to: " . print_r($this->remoteHostWhitelist, 1));
$this->log(
"Setting remote host whitelist to: "
. (is_null($whitelist) ? "null" : print_r($whitelist, 1))
);
return $this;
}
/**
* Check if the hostname for the remote image, is on a whitelist,
* Check if the hostname for the remote image, is on a whitelist,
* if the whitelist is defined.
*
* @param string $src the remote source.
@@ -472,14 +580,18 @@ class CImage
public function isRemoteSourceOnWhitelist($src)
{
if (is_null($this->remoteHostWhitelist)) {
$allow = true;
} else {
$whitelist = new CWhitelist();
$hostname = parse_url($src, PHP_URL_HOST);
$allow = $whitelist->check($hostname, $this->remoteHostWhitelist);
$this->log("Remote host on whitelist not configured - allowing.");
return true;
}
$this->log("Remote host is on whitelist: " . ($allow ? "true" : "false"));
$whitelist = new CWhitelist();
$hostname = parse_url($src, PHP_URL_HOST);
$allow = $whitelist->check($hostname, $this->remoteHostWhitelist);
$this->log(
"Remote host is on whitelist: "
. ($allow ? "true" : "false")
);
return $allow;
}
@@ -504,6 +616,26 @@ class CImage
/**
* Normalize the file extension.
*
* @param string $extension of image file or skip to use internal.
*
* @return string $extension as a normalized file extension.
*/
private function normalizeFileExtension($extension = null)
{
$extension = strtolower($extension ? $extension : $this->extension);
if ($extension == 'jpeg') {
$extension = 'jpg';
}
return $extension;
}
/**
* Download a remote image and return path to its local copy.
*
@@ -537,7 +669,7 @@ class CImage
$src = $remote->download($src);
$this->log("Remote HTTP status: " . $remote->getStatus());
$this->log("Remote item has local cached file: $src");
$this->log("Remote item is in local cache: $src");
$this->log("Remote details on cache:" . print_r($remote->getDetails(), true));
return $src;
@@ -546,16 +678,18 @@ class CImage
/**
* Set src file.
* Set source file to use as image source.
*
* @param string $src of image.
* @param string $dir as base directory where images are.
* @param string $dir as optional base directory where images are.
*
* @return $this
*/
public function setSource($src, $dir = null)
{
if (!isset($src)) {
$this->imageSrc = null;
$this->pathToImage = null;
return $this;
}
@@ -569,9 +703,9 @@ class CImage
$src = basename($src);
}
$this->imageSrc = ltrim($src, '/');
$this->imageFolder = rtrim($dir, '/');
$this->pathToImage = $this->imageFolder . '/' . $this->imageSrc;
$this->imageSrc = ltrim($src, '/');
$imageFolder = rtrim($dir, '/');
$this->pathToImage = $imageFolder . '/' . $this->imageSrc;
return $this;
}
@@ -582,23 +716,23 @@ class CImage
* Set target file.
*
* @param string $src of target image.
* @param string $dir as base directory where images are stored.
* @param string $dir as optional base directory where images are stored.
* Uses $this->saveFolder if null.
*
* @return $this
*/
public function setTarget($src = null, $dir = null)
{
if (!(isset($src) && isset($dir))) {
if (!isset($src)) {
$this->cacheFileName = null;
return $this;
}
$this->saveFolder = $dir;
$this->cacheFileName = $dir . '/' . $src;
if (isset($dir)) {
$this->saveFolder = rtrim($dir, '/');
}
/* Allow readonly cache
is_writable($this->saveFolder)
or $this->raiseError('Target directory is not writable.');
*/
$this->cacheFileName = $this->saveFolder . '/' . $src;
// Sanitize filename
$this->cacheFileName = preg_replace('/^a-zA-Z0-9\.-_/', '', $this->cacheFileName);
@@ -609,6 +743,18 @@ class CImage
/**
* Get filename of target file.
*
* @return Boolean|String as filename of target or false if not set.
*/
public function getTarget()
{
return $this->cacheFileName;
}
/**
* Set options to use when processing image.
*
@@ -656,11 +802,6 @@ class CImage
// Output format
'outputFormat' => null,
'dpr' => 1,
// Options for saving
//'quality' => null,
//'compress' => null,
//'saveAs' => null,
);
// Convert crop settings from string to array
@@ -777,7 +918,9 @@ class CImage
// Get details on image
$info = list($this->width, $this->height, $this->fileType, $this->attr) = getimagesize($file);
!empty($info) or $this->raiseError("The file doesn't seem to be an image.");
if (empty($info)) {
throw new Exception("The file doesn't seem to be a valid image.");
}
if ($this->verbose) {
$this->log("Loading image details for: {$file}");
@@ -974,7 +1117,7 @@ class CImage
$this->cropHeight = round($height / $ratio);
$this->log("Crop width, height, ratio: $this->cropWidth x $this->cropHeight ($ratio).");
} else if ($this->fillToFit) {
} elseif ($this->fillToFit) {
// Use newWidth and newHeigh as defined width/height,
// image should fit the area.
@@ -1152,13 +1295,15 @@ class CImage
/**
* Generate filename to save file in cache.
*
* @param string $base as basepath for storing file.
* @param string $base as optional basepath for storing file.
* @param boolean $useSubdir use or skip the subdir part when creating the
* filename.
*
* @return $this
*/
public function generateFilename($base)
public function generateFilename($base = null, $useSubdir = true)
{
$parts = pathinfo($this->pathToImage);
$filename = basename($this->pathToImage);
$cropToFit = $this->cropToFit ? '_cf' : null;
$fillToFit = $this->fillToFit ? '_ff' : null;
$crop_x = $this->crop_x ? "_x{$this->crop_x}" : null;
@@ -1170,6 +1315,14 @@ class CImage
$rotateBefore = $this->rotateBefore ? "_rb{$this->rotateBefore}" : null;
$rotateAfter = $this->rotateAfter ? "_ra{$this->rotateAfter}" : null;
$saveAs = $this->normalizeFileExtension();
$saveAs = $saveAs ? "_$saveAs" : null;
$copyStrat = null;
if ($this->copyStrategy === self::RESIZE) {
$copyStrat = "_rs";
}
$width = $this->newWidth;
$height = $this->newHeight;
@@ -1187,7 +1340,7 @@ class CImage
if (is_array($filter)) {
$filters .= "_f{$filter['id']}";
for ($i=1; $i<=$filter['argc']; $i++) {
$filters .= ":".$filter["arg{$i}"];
$filters .= "-".$filter["arg{$i}"];
}
}
}
@@ -1200,16 +1353,6 @@ class CImage
$autoRotate = $this->autoRotate ? 'ar' : null;
$this->extension = isset($this->extension)
? $this->extension
: (isset($parts['extension'])
? $parts['extension']
: null);
$extension = empty($this->extension)
? null
: "." . $this->extension;
$optimize = $this->jpegOptimize ? 'o' : null;
$optimize .= $this->pngFilter ? 'f' : null;
$optimize .= $this->pngDeflate ? 'd' : null;
@@ -1224,14 +1367,20 @@ class CImage
$upscale = '_nu';
}
$subdir = str_replace('/', '-', dirname($this->imageSrc));
$subdir = ($subdir == '.') ? '_.' : $subdir;
$file = $subdir . '_' . $parts['filename'] . '_' . $width . '_'
$subdir = null;
if ($useSubdir === true) {
$subdir = str_replace('/', '-', dirname($this->imageSrc));
$subdir = ($subdir == '.') ? '_.' : $subdir;
$subdir .= '_';
}
$file = $subdir . $filename . '_' . $width . '_'
. $height . $offset . $crop . $cropToFit . $fillToFit
. $crop_x . $crop_y . $upscale
. $quality . $filters . $sharpen . $emboss . $blur . $palette . $optimize
. $scale . $rotateBefore . $rotateAfter . $autoRotate . $bgColor . $convolve
. $extension;
. $quality . $filters . $sharpen . $emboss . $blur . $palette
. $optimize . $compress
. $scale . $rotateBefore . $rotateAfter . $autoRotate . $bgColor
. $convolve . $copyStrat . $saveAs;
return $this->setTarget($file, $base);
}
@@ -1274,23 +1423,7 @@ class CImage
/**
* To display error message when failing to load somehow corrupt image.
*
* @return void
*
*/
public function failedToLoad()
{
header("HTTP/1.0 404 Not Found");
echo("CImage.php says 404: Fatal error when opening image.<br>");
$image = imagecreatefromstring(file_get_contents($this->pathToImage));
exit();
}
/**
* Load image from disk. Try to load image without verbose error message,
* Load image from disk. Try to load image without verbose error message,
* if fail, load again and display error messages.
*
* @param string $src of image.
@@ -1307,9 +1440,12 @@ class CImage
$this->loadImageDetails($this->pathToImage);
$this->image = @imagecreatefromstring(file_get_contents($this->pathToImage));
$this->image or $this->failedToLoad();
$this->image = imagecreatefromstring(file_get_contents($this->pathToImage));
if ($this->image === false) {
throw new Exception("Could not load image.");
}
/* Removed v0.7.7
if (image_type_to_mime_type($this->fileType) == 'image/png') {
$type = $this->getPngType();
$hasFewColors = imagecolorstotal($this->image);
@@ -1321,14 +1457,15 @@ class CImage
$this->palette = true;
}
}
*/
if ($this->verbose) {
$this->log("Image successfully loaded from file.");
$this->log("### Image successfully loaded from file.");
$this->log(" imageistruecolor() : " . (imageistruecolor($this->image) ? 'true' : 'false'));
$this->log(" imagecolorstotal() : " . imagecolorstotal($this->image));
$this->log(" Number of colors in image = " . $this->colorsTotal($this->image));
$index = imagecolortransparent($this->image);
$this->log(" Detected transparent color = " . ($index > 0 ? implode(", ", imagecolorsforindex($this->image, $index)) : "NONE") . " at index = $index");
$this->log(" Detected transparent color = " . ($index >= 0 ? implode(", ", imagecolorsforindex($this->image, $index)) : "NONE") . " at index = $index");
}
return $this;
@@ -1339,44 +1476,80 @@ class CImage
/**
* Get the type of PNG image.
*
* @param string $filename to use instead of default.
*
* @return int as the type of the png-image
*
*/
private function getPngType()
public function getPngType($filename = null)
{
$pngType = ord(file_get_contents($this->pathToImage, false, null, 25, 1));
$filename = $filename ? $filename : $this->pathToImage;
$pngType = ord(file_get_contents($filename, false, null, 25, 1));
if ($this->verbose) {
$this->log("Checking png type of: " . $filename);
$this->log($this->getPngTypeAsString($pngType));
}
return $pngType;
}
/**
* Get the type of PNG image as a verbose string.
*
* @param integer $type to use, default is to check the type.
* @param string $filename to use instead of default.
*
* @return int as the type of the png-image
*
*/
private function getPngTypeAsString($pngType = null, $filename = null)
{
if ($filename || !$pngType) {
$pngType = $this->getPngType($filename);
}
$index = imagecolortransparent($this->image);
$transparent = null;
if ($index != -1) {
$transparent = " (transparent)";
}
switch ($pngType) {
case self::PNG_GREYSCALE:
$this->log("PNG is type 0, Greyscale.");
$text = "PNG is type 0, Greyscale$transparent";
break;
case self::PNG_RGB:
$this->log("PNG is type 2, RGB");
$text = "PNG is type 2, RGB$transparent";
break;
case self::PNG_RGB_PALETTE:
$this->log("PNG is type 3, RGB with palette");
$text = "PNG is type 3, RGB with palette$transparent";
break;
case self::PNG_GREYSCALE_ALPHA:
$this->Log("PNG is type 4, Greyscale with alpha channel");
$text = "PNG is type 4, Greyscale with alpha channel";
break;
case self::PNG_RGB_ALPHA:
$this->Log("PNG is type 6, RGB with alpha channel (PNG 32-bit)");
$text = "PNG is type 6, RGB with alpha channel (PNG 32-bit)";
break;
default:
$this->Log("PNG is UNKNOWN type, is it really a PNG image?");
$text = "PNG is UNKNOWN type, is it really a PNG image?";
}
return $pngType;
return $text;
}
/**
* Calculate number of colors in an image.
*
@@ -1412,7 +1585,7 @@ class CImage
*/
public function preResize()
{
$this->log("Pre-process before resizing");
$this->log("### Pre-process before resizing");
// Rotate image
if ($this->rotateBefore) {
@@ -1445,6 +1618,39 @@ class CImage
/**
* Resize or resample the image while resizing.
*
* @param int $strategy as CImage::RESIZE or CImage::RESAMPLE
*
* @return $this
*/
public function setCopyResizeStrategy($strategy)
{
$this->copyStrategy = $strategy;
return $this;
}
/**
* Resize and or crop the image.
*
* @return void
*/
public function imageCopyResampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
if($this->copyStrategy == self::RESIZE) {
$this->log("Copy by resize");
imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
} else {
$this->log("Copy by resample");
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
}
}
/**
* Resize and or crop the image.
*
@@ -1453,7 +1659,7 @@ class CImage
public function resize()
{
$this->log("Starting to Resize()");
$this->log("### Starting to Resize()");
$this->log("Upscale = '$this->upscale'");
// Only use a specified area of the image, $this->offset is defining the area to use
@@ -1513,7 +1719,7 @@ class CImage
$cropY = round(($this->cropHeight/2) - ($this->newHeight/2));
$imgPreCrop = $this->CreateImageKeepTransparency($this->cropWidth, $this->cropHeight);
$imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
imagecopyresampled($imgPreCrop, $this->image, 0, 0, 0, 0, $this->cropWidth, $this->cropHeight, $this->width, $this->height);
$this->imageCopyResampled($imgPreCrop, $this->image, 0, 0, 0, 0, $this->cropWidth, $this->cropHeight, $this->width, $this->height);
imagecopy($imageResized, $imgPreCrop, 0, 0, $cropX, $cropY, $this->newWidth, $this->newHeight);
}
@@ -1521,7 +1727,7 @@ class CImage
$this->width = $this->newWidth;
$this->height = $this->newHeight;
} else if ($this->fillToFit) {
} elseif ($this->fillToFit) {
// Resize by fill to fit
$this->log("Resizing using strategy - Fill to fit");
@@ -1552,7 +1758,7 @@ class CImage
} else {
$imgPreFill = $this->CreateImageKeepTransparency($this->fillWidth, $this->fillHeight);
$imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
imagecopyresampled($imgPreFill, $this->image, 0, 0, 0, 0, $this->fillWidth, $this->fillHeight, $this->width, $this->height);
$this->imageCopyResampled($imgPreFill, $this->image, 0, 0, 0, 0, $this->fillWidth, $this->fillHeight, $this->width, $this->height);
imagecopy($imageResized, $imgPreFill, $posX, $posY, 0, 0, $this->fillWidth, $this->fillHeight);
}
@@ -1560,7 +1766,7 @@ class CImage
$this->width = $this->newWidth;
$this->height = $this->newHeight;
} else if (!($this->newWidth == $this->width && $this->newHeight == $this->height)) {
} elseif (!($this->newWidth == $this->width && $this->newHeight == $this->height)) {
// Resize it
$this->log("Resizing, new height and/or width");
@@ -1581,10 +1787,10 @@ class CImage
if ($this->newWidth > $this->width && $this->newHeight > $this->height) {
$posX = round(($this->newWidth - $this->width) / 2);
$posY = round(($this->newHeight - $this->height) / 2);
} else if ($this->newWidth > $this->width) {
} elseif ($this->newWidth > $this->width) {
$posX = round(($this->newWidth - $this->width) / 2);
$cropY = round(($this->height - $this->newHeight) / 2);
} else if ($this->newHeight > $this->height) {
} elseif ($this->newHeight > $this->height) {
$posY = round(($this->newHeight - $this->height) / 2);
$cropX = round(($this->width - $this->newWidth) / 2);
}
@@ -1598,7 +1804,7 @@ class CImage
}
} else {
$imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
imagecopyresampled($imageResized, $this->image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
$this->imageCopyResampled($imageResized, $this->image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
$this->image = $imageResized;
$this->width = $this->newWidth;
$this->height = $this->newHeight;
@@ -1617,7 +1823,7 @@ class CImage
*/
public function postResize()
{
$this->log("Post-process after resizing");
$this->log("### Post-process after resizing");
// Rotate image
if ($this->rotateAfter) {
@@ -2013,7 +2219,10 @@ class CImage
imagealphablending($img, false);
imagesavealpha($img, true);
$index = imagecolortransparent($this->image);
$index = $this->image
? imagecolortransparent($this->image)
: -1;
if ($index != -1) {
imagealphablending($img, true);
@@ -2074,10 +2283,11 @@ class CImage
*/
protected function getTargetImageExtension()
{
// switch on mimetype
if (isset($this->extension)) {
return strtolower($this->extension);
} else {
return image_type_to_extension($this->fileType);
return substr(image_type_to_extension($this->fileType), 1);
}
}
@@ -2086,21 +2296,29 @@ class CImage
/**
* Save image.
*
* @param string $src as target filename.
* @param string $base as base directory where to store images.
* @param string $src as target filename.
* @param string $base as base directory where to store images.
* @param boolean $overwrite or not, default to always overwrite file.
*
* @return $this or false if no folder is set.
*/
public function save($src = null, $base = null)
public function save($src = null, $base = null, $overwrite = true)
{
if (isset($src)) {
$this->setTarget($src, $base);
}
if ($overwrite === false && is_file($this->cacheFileName)) {
$this->Log("Not overwriting file since its already exists and \$overwrite if false.");
return;
}
is_writable($this->saveFolder)
or $this->raiseError('Target directory is not writable.');
switch($this->getTargetImageExtension()) {
$type = $this->getTargetImageExtension();
$this->Log("Saving image as " . $type);
switch($type) {
case 'jpeg':
case 'jpg':
@@ -2194,8 +2412,6 @@ class CImage
return $this;
}
$alias = $alias . "." . $this->getTargetImageExtension();
if (is_readable($alias)) {
unlink($alias);
}
@@ -2213,11 +2429,28 @@ class CImage
/**
* Add HTTP header for putputting together with image.
*
* @param string $type the header type such as "Cache-Control"
* @param string $value the value to use
*
* @return void
*/
public function addHTTPHeader($type, $value)
{
$this->HTTPHeader[$type] = $value;
}
/**
* Output image to browser using caching.
*
* @param string $file to read and output, default is to use $this->cacheFileName
* @param string $format set to json to output file as json object with details
* @param string $file to read and output, default is to
* use $this->cacheFileName
* @param string $format set to json to output file as json
* object with details
*
* @return void
*/
@@ -2237,6 +2470,10 @@ class CImage
header('Content-type: application/json');
echo $this->json($file);
exit;
} elseif ($format == 'ascii') {
header('Content-type: text/plain');
echo $this->ascii($file);
exit;
}
$this->log("Outputting image: $file");
@@ -2250,6 +2487,10 @@ class CImage
header('Last-Modified: ' . $gmdate . " GMT");
}
foreach($this->HTTPHeader as $key => $val) {
header("$key: $val");
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified) {
if ($this->verbose) {
@@ -2262,18 +2503,25 @@ class CImage
} else {
if ($this->verbose) {
$this->log("Last modified: " . $gmdate . " GMT");
$this->verboseOutput();
exit;
}
// Get details on image
$info = getimagesize($file);
!empty($info) or $this->raiseError("The file doesn't seem to be an image.");
$mime = $info['mime'];
$size = filesize($file);
header('Content-type: ' . $mime);
if ($this->verbose) {
$this->log("Last-Modified: " . $gmdate . " GMT");
$this->log("Content-type: " . $mime);
$this->log("Content-length: " . $size);
$this->verboseOutput();
if (is_null($this->verboseFileName)) {
exit;
}
}
header("Content-type: $mime");
header("Content-length: $size");
readfile($file);
}
@@ -2314,6 +2562,18 @@ class CImage
$details['aspectRatio'] = round($this->width / $this->height, 3);
$details['size'] = filesize($file);
$details['colors'] = $this->colorsTotal($this->image);
$details['includedFiles'] = count(get_included_files());
$details['memoryPeek'] = round(memory_get_peak_usage()/1024/1024, 3) . " MB" ;
$details['memoryCurrent'] = round(memory_get_usage()/1024/1024, 3) . " MB";
$details['memoryLimit'] = ini_get('memory_limit');
if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
$details['loadTime'] = (string) round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']), 3) . "s";
}
if ($details['mimeType'] == 'image/png') {
$details['pngType'] = $this->getPngTypeAsString(null, $file);
}
$options = null;
if (defined("JSON_PRETTY_PRINT") && defined("JSON_UNESCAPED_SLASHES")) {
@@ -2325,6 +2585,38 @@ class CImage
/**
* Set options for creating ascii version of image.
*
* @param array $options empty to use default or set options to change.
*
* @return void.
*/
public function setAsciiOptions($options = array())
{
$this->asciiOptions = $options;
}
/**
* Create an ASCII version from the image details.
*
* @param string $file the file to output.
*
* @return string ASCII representation of the image.
*/
public function ascii($file = null)
{
$file = $file ? $file : $this->cacheFileName;
$asciiArt = new CAsciiArt();
$asciiArt->setOptions($this->asciiOptions);
return $asciiArt->createFromFile($file);
}
/**
* Log an event if verbose mode.
*
@@ -2343,6 +2635,21 @@ class CImage
/**
* Do verbose output to a file.
*
* @param string $fileName where to write the verbose output.
*
* @return void
*/
public function setVerboseToFile($fileName)
{
$this->log("Setting verbose output to file.");
$this->verboseFileName = $fileName;
}
/**
* Do verbose output and print out the log and the actual images.
*
@@ -2368,15 +2675,17 @@ class CImage
}
}
echo <<<EOD
<!doctype html>
<html lang=en>
<meta charset=utf-8>
<title>CImage verbose output</title>
<style>body{background-color: #ddd}</style>
if (!is_null($this->verboseFileName)) {
file_put_contents(
$this->verboseFileName,
str_replace("<br/>", "\n", $log)
);
} else {
echo <<<EOD
<h1>CImage Verbose Output</h1>
<pre>{$log}</pre>
EOD;
}
}

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-609156684"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1879794739"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-609156684" class="accordion-body collapse in">
<div id="namespace-1879794739" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -245,7 +246,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -48,7 +48,7 @@ class CRemoteImage
/**
* Base name of cache file for downloaded item.
* Base name of cache file for downloaded item and name of image.
*/
private $fileName;
@@ -61,13 +61,6 @@ class CRemoteImage
/**
* Filename for image-file.
*/
private $fileImage;
/**
* Cache details loaded from file.
*/
@@ -75,16 +68,6 @@ class CRemoteImage
/**
* Constructor
*
*/
public function __construct()
{
;
}
/**
* Get status of last HTTP request.
*
@@ -157,34 +140,14 @@ class CRemoteImage
/**
* Translate a content type to a file extension.
*
* @param string $type a valid content type.
*
* @return string as file extension or false if no match.
*/
function contentTypeToFileExtension($type) {
$extension = array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
);
return isset($extension[$type])
? $extension[$type]
: false;
}
/**
* Set header fields.
*
* @return $this
*/
function setHeaderFields() {
$this->http->setHeader("User-Agent", "CImage/0.6 (PHP/". phpversion() . " cURL)");
public function setHeaderFields()
{
$this->http->setHeader("User-Agent", "CImage/0.7.2 (PHP/". phpversion() . " cURL)");
$this->http->setHeader("Accept", "image/jpeg,image/png,image/gif");
if ($this->useCache) {
@@ -202,37 +165,31 @@ class CRemoteImage
*
* @return string as path to saved file or false if not saved.
*/
function save() {
public function save()
{
$this->cache = array();
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$type = $this->http->getContentType();
$extension = $this->contentTypeToFileExtension($type);
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
$this->cache['Content-Type'] = $type;
$this->cache['File-Extension'] = $extension;
$this->cache['Url'] = $this->url;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
if ($extension) {
// Save only if body is a valid image
$body = $this->http->getBody();
$img = imagecreatefromstring($body);
$this->fileImage = $this->fileName . "." . $extension;
// Save only if body is a valid image
$body = $this->http->getBody();
$img = imagecreatefromstring($body);
if ($img !== false) {
file_put_contents($this->fileImage, $body);
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileImage;
}
if ($img !== false) {
file_put_contents($this->fileName, $body);
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
}
return false;
@@ -245,21 +202,21 @@ class CRemoteImage
*
* @return string as path to cached file.
*/
function updateCacheDetails() {
public function updateCacheDetails()
{
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileImage;
return $this->fileName;
}
@@ -269,10 +226,12 @@ class CRemoteImage
*
* @param string $url a remote url.
*
* @throws Exception when status code does not match 200 or 304.
*
* @return string as path to downloaded file or false if failed.
*/
function download($url) {
public function download($url)
{
$this->http = new CHttpGet();
$this->url = $url;
@@ -296,12 +255,12 @@ class CRemoteImage
if ($this->status === 200) {
$this->isCacheWritable();
return $this->save();
} else if ($this->status === 304) {
} elseif ($this->status === 304) {
$this->isCacheWritable();
return $this->updateCacheDetails();
}
return false;
throw new Exception("Unknown statuscode when downloading remote image: " . $this->status);
}
@@ -313,7 +272,7 @@ class CRemoteImage
*/
public function loadCacheDetails()
{
$cacheFile = str_replace(array("/", ":", "#", ".", "?"), "-", $this->url);
$cacheFile = md5($this->url);
$this->fileName = $this->saveFolder . $cacheFile;
$this->fileJson = $this->fileName . ".json";
if (is_readable($this->fileJson)) {
@@ -330,15 +289,15 @@ class CRemoteImage
*/
public function getCachedSource()
{
$this->fileImage = $this->fileName . "." . $this->cache['File-Extension'];
$imageExists = is_readable($this->fileImage);
$imageExists = is_readable($this->fileName);
// Is cache valid?
$date = strtotime($this->cache['Date']);
$maxAge = $this->cache['Max-Age'];
$now = time();
$now = time();
if ($imageExists && $date + $maxAge > $now) {
return $this->fileImage;
return $this->fileName;
}
// Prepare for a 304 if available

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1345074256"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-1920829892"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-1345074256" class="accordion-body collapse in">
<div id="namespace-1920829892" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -245,7 +246,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -13,21 +13,21 @@ class CWhitelist
/**
* Set the whitelist from an array of strings, each item in the
* Set the whitelist from an array of strings, each item in the
* whitelist should be a regexp without the surrounding / or #.
*
* @param array $whitelist with all valid options,
* @param array $whitelist with all valid options,
* default is to clear the whitelist.
*
* @return $this
*/
public function set($whitelist = array())
{
if (is_array($whitelist)) {
$this->whitelist = $whitelist;
} else {
if (!is_array($whitelist)) {
throw new Exception("Whitelist is not of a supported format.");
}
$this->whitelist = $whitelist;
return $this;
}
@@ -44,8 +44,8 @@ class CWhitelist
public function check($item, $whitelist = null)
{
if ($whitelist !== null) {
$this->set($whitelist);
}
$this->set($whitelist);
}
if (empty($item) or empty($this->whitelist)) {
return false;

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-716918064"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-105414451"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-716918064" class="accordion-body collapse in">
<div id="namespace-105414451" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -238,7 +239,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -17,7 +17,7 @@
spl_autoload_register(function ($class) {
//$path = CIMAGE_SOURCE_PATH . "/{$class}.php";
$path = __DIR__ . "/{$class}.php";
if(is_file($path)) {
if (is_file($path)) {
require($path);
}
});

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-110318675"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-543265601"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-110318675" class="accordion-body collapse in">
<div id="namespace-543265601" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -219,7 +220,7 @@
<h3 class=" ">errorPage()</h3>
<a href="#source-view" role="button" class="pull-right btn" data-toggle="modal" style="font-size: 1.1em; padding: 9px 14px"><i class="icon-code"></i></a>
<pre class="signature" style="margin-right: 54px;">errorPage(string <span class="argument">$msg</span>) : void</pre>
<p><em>Default configuration options, can be overridden in own config-file.</em></p>
<p><em>Display error message.</em></p>
<h4>Parameters</h4>
@@ -506,7 +507,7 @@
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

View File

@@ -106,12 +106,12 @@
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">27</span>
<i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">40</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">164</span>
<i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
@@ -136,15 +136,16 @@
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-805317831"></a>
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-112631378"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-805317831" class="accordion-body collapse in">
<div id="namespace-112631378" class="accordion-body collapse in">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CAsciiArt.html">CAsciiArt</a></li>
<li class="class"><a href="../classes/CHttpGet.html">CHttpGet</a></li>
<li class="class"><a href="../classes/CImage.html">CImage</a></li>
<li class="class"><a href="../classes/CRemoteImage.html">CRemoteImage</a></li>
<li class="class"><a href="../classes/CWhitelist.html">CWhitelist</a></li>
@@ -240,7 +241,7 @@ config-file imgtest_config.php.</em></p>
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 6th, 2015 at 12:38.
on December 2nd, 2015 at 11:04.
</section>
</section>
</section>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,386 @@
<?php
/**
* Configuration for img.php, name the config file the same as your img.php and
* append _config. If you are testing out some in imgtest.php then label that
* config-file imgtest_config.php.
*
*/
return array(
/**
* Set mode as 'strict', 'production' or 'development'.
*
* Default values:
* mode: 'production'
*/
//'mode' => 'production', // 'development', 'strict'
/**
* Where are the sources for the classfiles.
*
* Default values:
* autoloader: null // used from v0.6.2
* cimage_class: null // used until v0.6.1
*/
'autoloader' => __DIR__ . '/../autoload.php',
//'cimage_class' => __DIR__ . '/../CImage.php',
/**
* Paths, where are the images stored and where is the cache.
* End all paths with a slash.
*
* Default values:
* image_path: __DIR__ . '/img/'
* cache_path: __DIR__ . '/../cache/'
* alias_path: null
*/
'image_path' => __DIR__ . '/img/',
'cache_path' => __DIR__ . '/../cache/',
//'alias_path' => __DIR__ . '/img/alias/',
/**
* Use password to protect from missusage, send &pwd=... or &password=..
* with the request to match the password or set to false to disable.
* Passwords are only used together with options for remote download
* and aliasing.
*
* Create a passwords like this, depending on the type used:
* text: 'my_password'
* md5: md5('my_password')
* hash: password_hash('my_password', PASSWORD_DEFAULT)
*
* Default values.
* password_always: false // do not always require password,
* password: false // as in do not use password
* password_type: 'text' // use plain password, not encoded,
*/
//'password_always' => false, // always require password,
//'password' => false, // "secret-password",
//'password_type' => 'text', // supports 'text', 'md5', 'hash',
/**
* Allow or disallow downloading of remote images available on
* remote servers. Default is to disallow remote download.
*
* When enabling remote download, the default is to allow download any
* link starting with http or https. This can be changed using
* remote_pattern.
*
* When enabling remote_whitelist a check is made that the hostname of the
* source to download matches the whitelist. By default the check is
* disabled and thereby allowing download from any hosts.
*
* Default values.
* remote_allow: false
* remote_pattern: null // use default values from CImage which is to
* // allow download from any http- and
* // https-source.
* remote_whitelist: null // use default values from CImage which is to
* // allow download from any hosts.
*/
//'remote_allow' => true,
//'remote_pattern' => '#^https?://#',
//'remote_whitelist' => array(
// '\.facebook\.com$',
// '^(?:images|photos-[a-z])\.ak\.instagram\.com$',
// '\.google\.com$'
//),
/**
* A regexp for validating characters in the image or alias filename.
*
* Default value:
* valid_filename: '#^[a-z0-9A-Z-/_ \.:]+$#'
* valid_aliasname: '#^[a-z0-9A-Z-_]+$#'
*/
//'valid_filename' => '#^[a-z0-9A-Z-/_ \.:]+$#',
//'valid_aliasname' => '#^[a-z0-9A-Z-_]+$#',
/**
* Change the default values for CImage quality and compression used
* when saving images.
*
* Default value:
* jpg_quality: null, integer between 0-100
* png_compression: null, integer between 0-9
*/
//'jpg_quality' => 75,
//'png_compression' => 1,
/**
* A function (hook) can be called after img.php has processed all
* configuration options and before processing the image using CImage.
* The function receives the $img variabel and an array with the
* majority of current settings.
*
* Default value:
* hook_before_CImage: null
*/
/*'hook_before_CImage' => function (CImage $img, Array $allConfig) {
if ($allConfig['newWidth'] > 10) {
$allConfig['newWidth'] *= 2;
}
return $allConfig;
},*/
/**
* Add header for cache control when outputting images.
*
* Default value:
* cache_control: null, or set to string
*/
//'cache_control' => "max-age=86400",
/**
* The name representing a dummy image which is automatically created
* and stored at the defined path. The dummy image can then be used
* inplace of an original image as a placeholder.
* The dummy_dir must be writable and it defaults to a subdir of the
* cache directory.
* Write protect the dummy_dir to prevent creation of new dummy images,
* but continue to use the existing ones.
*
* Default value:
* dummy_enabled: true as default, disable dummy feature by setting
* to false.
* dummy_filename: 'dummy' use this as ?src=dummy to create a dummy image.
* dummy_dir: Defaults to subdirectory of 'cache_path',
* named the same as 'dummy_filename'
*/
//'dummy_enabled' => true,
//'dummy_filename' => 'dummy',
//'dummy_dir' => 'some writable directory',
/**
* Check that the imagefile is a file below 'image_path' using realpath().
* Security constraint to avoid reaching images outside image_path.
* This means that symbolic links to images outside the image_path will fail.
*
* Default value:
* image_path_constraint: true
*/
//'image_path_constraint' => false,
/**
* Set default timezone.
*
* Default values.
* default_timezone: ini_get('default_timezone') or 'UTC'
*/
//'default_timezone' => 'UTC',
/**
* Max image dimensions, larger dimensions results in 404.
* This is basically a security constraint to avoid using resources on creating
* large (unwanted) images.
*
* Default values.
* max_width: 2000
* max_height: 2000
*/
//'max_width' => 2000,
//'max_height' => 2000,
/**
* Set default background color for all images. Override it using
* option bgColor.
* Colorvalue is 6 digit hex string between 000000-FFFFFF
* or 8 digit hex string if using the alpha channel where
* the alpha value is between 00 (opaqe) and 7F (transparent),
* that is between 00000000-FFFFFF7F.
*
* Default values.
* background_color: As specified by CImage
*/
//'background_color' => "FFFFFF",
//'background_color' => "FFFFFF7F",
/**
* Post processing of images using external tools, set to true or false
* and set command to be executed.
*
* Default values.
*
* png_filter: false
* png_filter_cmd: '/usr/local/bin/optipng -q'
*
* png_deflate: false
* png_deflate_cmd: '/usr/local/bin/pngout -q'
*
* jpeg_optimize: false
* jpeg_optimize_cmd: '/usr/local/bin/jpegtran -copy none -optimize'
*/
/*
'postprocessing' => array(
'png_filter' => false,
'png_filter_cmd' => '/usr/local/bin/optipng -q',
'png_deflate' => false,
'png_deflate_cmd' => '/usr/local/bin/pngout -q',
'jpeg_optimize' => false,
'jpeg_optimize_cmd' => '/usr/local/bin/jpegtran -copy none -optimize',
),
*/
/**
* Create custom convolution expressions, matrix 3x3, divisor and
* offset.
*
* Default values.
* convolution_constant: array()
*/
/*
'convolution_constant' => array(
//'sharpen' => '-1,-1,-1, -1,16,-1, -1,-1,-1, 8, 0',
//'sharpen-alt' => '0,-1,0, -1,5,-1, 0,-1,0, 1, 0',
),
*/
/**
* Prevent leeching of images by controlling the hostname of those who
* can access the images. Default is to allow hotlinking.
*
* Password apply when hotlinking is disallowed, use password to allow
* hotlinking.
*
* The whitelist is an array of regexpes for allowed hostnames that can
* hotlink images.
*
* Default values.
* allow_hotlinking: true
* hotlinking_whitelist: array()
*/
/*
'allow_hotlinking' => false,
'hotlinking_whitelist' => array(
'^dbwebb\.se$',
),
*/
/**
* Create custom shortcuts for more advanced expressions.
*
* Default values.
* shortcut: array(
* 'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
* )
*/
/*
'shortcut' => array(
'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
),*/
/**
* Predefined size constants.
*
* These can be used together with &width or &height to create a constant value
* for a width or height where can be changed in one place.
* Useful when your site changes its layout or if you have a grid to fit images into.
*
* Example:
* &width=w1 // results in width=613
* &width=c2 // results in spanning two columns with a gutter, 30*2+10=70
* &width=c24 // results in spanning whole grid 24*30+((24-1)*10)=950
*
* Default values.
* size_constant: As specified by the function below.
*/
/*
'size_constant' => function () {
// Set sizes to map constant to value, easier to use with width or height
$sizes = array(
'w1' => 613,
'w2' => 630,
);
// Add grid column width, useful for use as predefined size for width (or height).
$gridColumnWidth = 30;
$gridGutterWidth = 10;
$gridColumns = 24;
for ($i = 1; $i <= $gridColumns; $i++) {
$sizes['c' . $i] = ($gridColumnWidth + $gridGutterWidth) * $i - $gridGutterWidth;
}
return $sizes;
},*/
/**
* Predefined aspect ratios.
*
* Default values.
* aspect_ratio_constant: As the function below.
*/
/*'aspect_ratio_constant' => function () {
return array(
'3:1' => 3/1,
'3:2' => 3/2,
'4:3' => 4/3,
'8:5' => 8/5,
'16:10' => 16/10,
'16:9' => 16/9,
'golden' => 1.618,
);
},*/
/**
* default options for ascii image.
*
* Default values as specified below in the array.
* ascii-options:
* characterSet: Choose any character set available in CAsciiArt.
* scale: How many pixels should each character
* translate to.
* luminanceStrategy: Choose any strategy available in CAsciiArt.
* customCharacterSet: Define your own character set.
*/
/*'ascii-options' => array(
"characterSet" => 'two',
"scale" => 14,
"luminanceStrategy" => 3,
"customCharacterSet" => null,
);
},*/
);