\CImage

Resize and crop images on the fly, store generated images in a cache.

Examples

** File not found : http://dbwebb.se/opensource/cimage **

Summary

Methods
Properties
Constants
__construct()
setVerbose()
setSaveFolder()
useCache()
createDummyImage()
setRemoteDownload()
isRemoteSource()
setRemoteHostWhitelist()
isRemoteSourceOnWhitelist()
downloadRemoteSource()
setSource()
setTarget()
getTarget()
setOptions()
loadImageDetails()
initDimensions()
calculateNewWidthAndHeight()
reCalculateDimensions()
setSaveAsExtension()
setJpegQuality()
setPngCompression()
useOriginalIfPossible()
generateFilename()
useCacheIfPossible()
load()
getPngType()
preResize()
setCopyResizeStrategy()
imageCopyResampled()
resize()
postResize()
rotate()
rotateExif()
trueColorToPalette()
sharpenImage()
embossImage()
blurImage()
createConvolveArguments()
addConvolveExpressions()
imageConvolution()
setDefaultBackgroundColor()
setPostProcessingOptions()
save()
linkToCacheFile()
addHTTPHeader()
output()
json()
setAsciiOptions()
ascii()
log()
setVerboseToFile()
$crop
$cropOrig
$keepRatio
$cropToFit
$crop_x
$crop_y
$filters
PNG_GREYSCALE
PNG_RGB
PNG_RGB_PALETTE
PNG_GREYSCALE_ALPHA
PNG_RGB_ALPHA
JPEG_QUALITY_DEFAULT
PNG_COMPRESSION_DEFAULT
UPSCALE_DEFAULT
RESIZE
RESAMPLE
getTargetImageExtension()
No protected properties found
N/A
checkFileExtension()
normalizeFileExtension()
mapFilter()
getPngTypeAsString()
colorsTotal()
getBackgroundColor()
createImageKeepTransparency()
verboseOutput()
raiseError()
$quality
$useQuality
$compress
$useCompress
$HTTPHeader
$bgColorDefault
$bgColor
$saveFolder
$image
$imageSrc
$pathToImage
$fileType
$extension
$outputFormat
$verbose
$log
$palette
$cacheFileName
$saveAs
$pngFilter
$pngFilterCmd
$pngDeflate
$pngDeflateCmd
$jpegOptimize
$jpegOptimizeCmd
$width
$height
$newWidth
$newWidthOrig
$newHeight
$newHeightOrig
$dpr
$upscale
$convolve
$convolves
$fillToFit
$scale
$rotateBefore
$rotateAfter
$autoRotate
$sharpen
$emboss
$blur
$offset
$fillWidth
$fillHeight
$allowRemote
$remotePattern
$useCache
$remoteHostWhitelist
$verboseFileName
$asciiOptions
$copyStrategy
$cropWidth
$cropHeight
$attr
N/A

Constants

PNG_GREYSCALE

PNG_GREYSCALE

Constants type of PNG image

PNG_RGB

PNG_RGB

PNG_RGB_PALETTE

PNG_RGB_PALETTE

PNG_GREYSCALE_ALPHA

PNG_GREYSCALE_ALPHA

PNG_RGB_ALPHA

PNG_RGB_ALPHA

JPEG_QUALITY_DEFAULT

JPEG_QUALITY_DEFAULT

Constant for default image quality when not set

PNG_COMPRESSION_DEFAULT

PNG_COMPRESSION_DEFAULT

Constant for default image quality when not set

UPSCALE_DEFAULT

UPSCALE_DEFAULT

Always upscale images, even if they are smaller than target image.

RESIZE

RESIZE

RESAMPLE

RESAMPLE

Properties

$crop

$crop : 

Array with details on how to crop, incoming as argument and calculated.

Type

$cropOrig

$cropOrig : 

Type

$keepRatio

$keepRatio : 

Properties, the class is mutable and the method setOptions() decides (partly) what properties are created.

Type

$cropToFit

$cropToFit : 

Type

$crop_x

$crop_x : 

Type

$crop_y

$crop_y : 

Type

$filters

$filters : 

Type

$quality

$quality : 

Quality level for JPEG images.

Type

$useQuality

$useQuality : 

Is the quality level set from external use (true) or is it default (false)?

Type

$compress

$compress : 

Compression level for PNG images.

Type

$useCompress

$useCompress : 

Is the compress level set from external use (true) or is it default (false)?

Type

$HTTPHeader

$HTTPHeader : 

Add HTTP headers for outputing image.

Type

$bgColorDefault

$bgColorDefault : 

Type

$bgColor

$bgColor : 

Background color to use, specified as part of options.

Type

$saveFolder

$saveFolder : 

Where to save the target file.

Type

$image

$image : 

The working image object.

Type

$imageSrc

$imageSrc : 

Image filename, may include subdirectory, relative from $imageFolder

Type

$pathToImage

$pathToImage : 

Actual path to the image, $imageFolder . '/' . $imageSrc

Type

$fileType

$fileType : 

File type for source image, as provided by getimagesize()

Type

$extension

$extension : 

File extension to use when saving image.

Type

$outputFormat

$outputFormat : 

Output format, supports null (image) or json.

Type

$verbose

$verbose : 

Verbose mode to print out a trace and display the created image

Type

$log

$log : 

Keep a log/trace on what happens

Type

$palette

$palette : 

Handle image as palette image

Type

$cacheFileName

$cacheFileName : 

Target filename, with path, to save resulting image in.

Type

$saveAs

$saveAs : 

Set a format to save image as, or null to use original format.

Type

$pngFilter

$pngFilter : 

Path to command for filter optimize, for example optipng or null.

Type

$pngFilterCmd

$pngFilterCmd : 

Type

$pngDeflate

$pngDeflate : 

Path to command for deflate optimize, for example pngout or null.

Type

$pngDeflateCmd

$pngDeflateCmd : 

Type

$jpegOptimize

$jpegOptimize : 

Path to command to optimize jpeg images, for example jpegtran or null.

Type

$jpegOptimizeCmd

$jpegOptimizeCmd : 

Type

$width

$width : 

Image dimensions, calculated from loaded image.

Type

$height

$height : 

Type

$newWidth

$newWidth : 

New image dimensions, incoming as argument or calculated.

Type

$newWidthOrig

$newWidthOrig : 

Type

$newHeight

$newHeight : 

Type

$newHeightOrig

$newHeightOrig : 

Type

$dpr

$dpr : 

Change target height & width when different dpr, dpr 2 means double image dimensions.

Type

$upscale

$upscale : 

Type

$convolve

$convolve : 

String with details on how to do image convolution. String should map a key in the $convolvs array or be a string of 11 float values separated by comma. The first nine builds up the matrix, then divisor and last offset.

Type

$convolves

$convolves : 

Custom convolution expressions, matrix 3x3, divisor and offset.

Type

$fillToFit

$fillToFit : 

Resize strategy to fill extra area with background color.

True or false.

Type

$scale

$scale : 

To store value for option scale.

Type

$rotateBefore

$rotateBefore : 

To store value for option.

Type

$rotateAfter

$rotateAfter : 

To store value for option.

Type

$autoRotate

$autoRotate : 

To store value for option.

Type

$sharpen

$sharpen : 

To store value for option.

Type

$emboss

$emboss : 

To store value for option.

Type

$blur

$blur : 

To store value for option.

Type

$offset

$offset : 

Used with option area to set which parts of the image to use.

Type

$fillWidth

$fillWidth : 

Calculate target dimension for image when using fill-to-fit resize strategy.

Type

$fillHeight

$fillHeight : 

Type

$allowRemote

$allowRemote : 

Allow remote file download, default is to disallow remote file download.

Type

$remotePattern

$remotePattern : 

Type

$useCache

$useCache : 

Use the cache if true, set to false to ignore the cached file.

Type

$remoteHostWhitelist

$remoteHostWhitelist : 

Type

$verboseFileName

$verboseFileName : 

Type

$asciiOptions

$asciiOptions : 

Type

$copyStrategy

$copyStrategy : 

Type

$cropWidth

$cropWidth : 

Type

$cropHeight

$cropHeight : 

Type

$attr

$attr : 

Type

Methods

__construct()

__construct(string  $imageSrc = null, string  $imageFolder = null, string  $saveFolder = null, string  $saveName = null) 

Constructor, can take arguments to init the object.

Parameters

string $imageSrc

filename which may contain subdirectory.

string $imageFolder

path to root folder for images.

string $saveFolder

path to folder where to save the new file or null to skip saving.

string $saveName

name of target file when saveing.

setVerbose()

setVerbose(boolean  $mode = true) : $this

Set verbose mode.

Parameters

boolean $mode

true or false to enable and disable verbose mode, default is true.

Returns

$this

setSaveFolder()

setSaveFolder(string  $path) : $this

Set save folder, base folder for saving cache files.

Parameters

string $path

where to store cached files.

Returns

$this

useCache()

useCache(boolean  $use = true) : $this

Use cache or not.

Parameters

boolean $use

true or false to use cache.

Returns

$this

createDummyImage()

createDummyImage(integer  $width = null, integer  $height = null) : $this

Create and save a dummy image. Use dimensions as stated in $this->newWidth, or $width or default to 100 (same for height.

Parameters

integer $width

use specified width for image dimension.

integer $height

use specified width for image dimension.

Returns

$this

setRemoteDownload()

setRemoteDownload(boolean  $allow, string  $pattern = null) : $this

Allow or disallow remote image download.

Parameters

boolean $allow

true or false to enable and disable.

string $pattern

to use to detect if its a remote file.

Returns

$this

isRemoteSource()

isRemoteSource(string  $src) : boolean

Check if the image resource is a remote file or not.

Parameters

string $src

check if src is remote.

Returns

boolean —

true if $src is a remote file, else false.

setRemoteHostWhitelist()

setRemoteHostWhitelist(array  $whitelist = null) : $this

Set whitelist for valid hostnames from where remote source can be downloaded.

Parameters

array $whitelist

with regexp hostnames to allow download from.

Returns

$this

isRemoteSourceOnWhitelist()

isRemoteSourceOnWhitelist(string  $src) : boolean

Check if the hostname for the remote image, is on a whitelist, if the whitelist is defined.

Parameters

string $src

the remote source.

Returns

boolean —

true if hostname on $src is in the whitelist, else false.

downloadRemoteSource()

downloadRemoteSource(string  $src) : string

Download a remote image and return path to its local copy.

Parameters

string $src

remote path to image.

Returns

string —

as path to downloaded remote source.

setSource()

setSource(string  $src, string  $dir = null) : $this

Set source file to use as image source.

Parameters

string $src

of image.

string $dir

as optional base directory where images are.

Returns

$this

setTarget()

setTarget(string  $src = null, string  $dir = null) : $this

Set target file.

Parameters

string $src

of target image.

string $dir

as optional base directory where images are stored. Uses $this->saveFolder if null.

Returns

$this

getTarget()

getTarget() : Boolean|String

Get filename of target file.

Returns

Boolean|String —

as filename of target or false if not set.

setOptions()

setOptions(array  $args) : $this

Set options to use when processing image.

Parameters

array $args

used when processing image.

Returns

$this

loadImageDetails()

loadImageDetails(string  $file = null) : $this

Load image details from original image file.

Parameters

string $file

the file to load or null to use $this->pathToImage.

Throws

\Exception

Returns

$this

initDimensions()

initDimensions() : $this

Init new width and height and do some sanity checks on constraints, before any processing can be done.

Throws

\Exception

Returns

$this

calculateNewWidthAndHeight()

calculateNewWidthAndHeight() : $this

Calculate new width and height of image, based on settings.

Returns

$this

reCalculateDimensions()

reCalculateDimensions() : $this

Re-calculate image dimensions when original image dimension has changed.

Returns

$this

setSaveAsExtension()

setSaveAsExtension(  $saveAs = null) : $this

Set extension for filename to save as.

Parameters

$saveAs

Returns

$this

setJpegQuality()

setJpegQuality(integer  $quality = null) : $this

Set JPEG quality to use when saving image

Parameters

integer $quality

as the quality to set.

Returns

$this

setPngCompression()

setPngCompression(integer  $compress = null) : $this

Set PNG compressen algorithm to use when saving image

Parameters

integer $compress

as the algorithm to use.

Returns

$this

useOriginalIfPossible()

useOriginalIfPossible(boolean  $useOrig = true) : $this

Use original image if possible, check options which affects image processing.

Parameters

boolean $useOrig

default is to use original if possible, else set to false.

Returns

$this

generateFilename()

generateFilename(string  $base = null, boolean  $useSubdir = true) : $this

Generate filename to save file in cache.

Parameters

string $base

as optional basepath for storing file.

boolean $useSubdir

use or skip the subdir part when creating the filename.

Returns

$this

useCacheIfPossible()

useCacheIfPossible(boolean  $useCache = true) : $this

Use cached version of image, if possible.

Parameters

boolean $useCache

is default true, set to false to avoid using cached object.

Returns

$this

load()

load(string  $src = null, string  $dir = null) : $this

Load image from disk. Try to load image without verbose error message, if fail, load again and display error messages.

Parameters

string $src

of image.

string $dir

as base directory where images are.

Returns

$this

getPngType()

getPngType(string  $filename = null) : integer

Get the type of PNG image.

Parameters

string $filename

to use instead of default.

Returns

integer —

as the type of the png-image

preResize()

preResize() : $this

Preprocess image before rezising it.

Returns

$this

setCopyResizeStrategy()

setCopyResizeStrategy(integer  $strategy) : $this

Resize or resample the image while resizing.

Parameters

integer $strategy

as CImage::RESIZE or CImage::RESAMPLE

Returns

$this

imageCopyResampled()

imageCopyResampled(  $dst_image,   $src_image,   $dst_x,   $dst_y,   $src_x,   $src_y,   $dst_w,   $dst_h,   $src_w,   $src_h) : void

Resize and or crop the image.

Parameters

$dst_image
$src_image
$dst_x
$dst_y
$src_x
$src_y
$dst_w
$dst_h
$src_w
$src_h

resize()

resize() : $this

Resize and or crop the image.

Returns

$this

postResize()

postResize() : $this

Postprocess image after rezising image.

Returns

$this

rotate()

rotate(float  $angle,   $bgColor) : $this

Rotate image using angle.

Parameters

float $angle

to rotate image.

$bgColor

Returns

$this

rotateExif()

rotateExif() : $this

Rotate image using information in EXIF.

Returns

$this

sharpenImage()

sharpenImage() : $this

Sharpen image using image convolution.

Returns

$this

embossImage()

embossImage() : $this

Emboss image using image convolution.

Returns

$this

blurImage()

blurImage() : $this

Blur image using image convolution.

Returns

$this

createConvolveArguments()

createConvolveArguments(string  $expression) : array

Create convolve expression and return arguments for image convolution.

Parameters

string $expression

constant string which evaluates to a list of 11 numbers separated by komma or such a list.

Returns

array —

as $matrix (3x3), $divisor and $offset

addConvolveExpressions()

addConvolveExpressions(array  $options) : $this

Add custom expressions (or overwrite existing) for image convolution.

Parameters

array $options

Key value array with strings to be converted to convolution expressions.

Returns

$this

imageConvolution()

imageConvolution(string  $options = null) : $this

Image convolution.

Parameters

string $options

A string with 11 float separated by comma.

Returns

$this

setDefaultBackgroundColor()

setDefaultBackgroundColor(string  $color) : $this

Set default background color between 000000-FFFFFF or if using alpha 00000000-FFFFFF7F.

Parameters

string $color

as hex value.

Returns

$this

setPostProcessingOptions()

setPostProcessingOptions(array  $options) : $this

Set optimizing and post-processing options.

Parameters

array $options

with config for postprocessing with external tools.

Returns

$this

save()

save(string  $src = null, string  $base = null, boolean  $overwrite = true) : $this

Save image.

Parameters

string $src

as target filename.

string $base

as base directory where to store images.

boolean $overwrite

or not, default to always overwrite file.

Returns

$this —

or false if no folder is set.

linkToCacheFile()

linkToCacheFile(string  $alias) : $this

Create a hard link, as an alias, to the cached file.

Parameters

string $alias

where to store the link, filename without extension.

Returns

$this

addHTTPHeader()

addHTTPHeader(string  $type, string  $value) : void

Add HTTP header for putputting together with image.

Parameters

string $type

the header type such as "Cache-Control"

string $value

the value to use

output()

output(string  $file = null, string  $format = null) : void

Output image to browser using caching.

Parameters

string $file

to read and output, default is to use $this->cacheFileName

string $format

set to json to output file as json object with details

json()

json(string  $file = null) : string

Create a JSON object from the image details.

Parameters

string $file

the file to output.

Returns

string —

json-encoded representation of the image.

setAsciiOptions()

setAsciiOptions(array  $options = array()) : \void.

Set options for creating ascii version of image.

Parameters

array $options

empty to use default or set options to change.

Returns

\void.

ascii()

ascii(string  $file = null) : string

Create an ASCII version from the image details.

Parameters

string $file

the file to output.

Returns

string —

ASCII representation of the image.

log()

log(string  $message) : \this

Log an event if verbose mode.

Parameters

string $message

to log.

Returns

\this

setVerboseToFile()

setVerboseToFile(string  $fileName) : void

Do verbose output to a file.

Parameters

string $fileName

where to write the verbose output.

getTargetImageExtension()

getTargetImageExtension() : string

Find out the type (file extension) for the image to be saved.

Returns

string —

as image extension.

checkFileExtension()

checkFileExtension(string  $extension) : $this

Check if file extension is valid as a file extension.

Parameters

string $extension

of image file.

Returns

$this

normalizeFileExtension()

normalizeFileExtension(string  $extension = null) : string

Normalize the file extension.

Parameters

string $extension

of image file or skip to use internal.

Returns

string —

$extension as a normalized file extension.

mapFilter()

mapFilter(string  $name) : array

Map filter name to PHP filter and id.

Parameters

string $name

the name of the filter.

Throws

\Exception

Returns

array —

with filter settings

getPngTypeAsString()

getPngTypeAsString(  $pngType = null, string  $filename = null) : integer

Get the type of PNG image as a verbose string.

Parameters

$pngType
string $filename

to use instead of default.

Returns

integer —

as the type of the png-image

colorsTotal()

colorsTotal(resource  $im) : integer

Calculate number of colors in an image.

Parameters

resource $im

the image.

Returns

integer

getBackgroundColor()

getBackgroundColor(resource  $img = null) : \color

Get the background color.

Parameters

resource $img

the image to work with or null if using $this->image.

Returns

\color —

value or null if no background color is set.

createImageKeepTransparency()

createImageKeepTransparency(integer  $width, integer  $height) : \image

Create a image and keep transparency for png and gifs.

Parameters

integer $width

of the new image.

integer $height

of the new image.

Returns

\image —

resource.

verboseOutput()

verboseOutput() : void

Do verbose output and print out the log and the actual images.

raiseError()

raiseError(string  $message) : void

Raise error, enables to implement a selection of error methods.

Parameters

string $message

the error message to display.

Throws

\Exception