# \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

File
  CImage.php
Package
  Default
Class hierarchy
  \CImage
See also
  https://github.com/mosbth/cimage

## Tags

author | Mikael Roos mos@dbwebb.se

## Constants

### PNG_GREYSCALE

    PNG_GREYSCALE

Constants type of PNG image

#

## Tags

None found

### PNG_RGB

    PNG_RGB

#

## Tags

None found

### PNG_RGB_PALETTE

    PNG_RGB_PALETTE

#

## Tags

None found

### PNG_GREYSCALE_ALPHA

    PNG_GREYSCALE_ALPHA

#

## Tags

None found

### PNG_RGB_ALPHA

    PNG_RGB_ALPHA

#

## Tags

None found

### JPEG_QUALITY_DEFAULT

    JPEG_QUALITY_DEFAULT

Constant for default image quality when not set

#

## Tags

None found

### PNG_COMPRESSION_DEFAULT

    PNG_COMPRESSION_DEFAULT

Constant for default image quality when not set

#

## Tags

None found

### UPSCALE_DEFAULT

    UPSCALE_DEFAULT

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

#

## Tags

None found

### RESIZE

    RESIZE

#

## Tags

None found

### RESAMPLE

    RESAMPLE

#

## Tags

None found

## Properties

### $crop

    $crop :

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

#### Type

#

## Tags

None found

### $cropOrig

    $cropOrig :

#### Type

#

## Tags

None found

### $keepRatio

    $keepRatio :

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

#### Type

#

## Tags

todo | Clean up these and check if and how they are used

### $cropToFit

    $cropToFit :

#### Type

#

## Tags

None found

### $crop_x

    $crop_x :

#### Type

#

## Tags

None found

### $crop_y

    $crop_y :

#### Type

#

## Tags

None found

### $filters

    $filters :

#### Type

#

## Tags

None found

### $quality

    $quality :

Quality level for JPEG images.

#### Type

#

## Tags

None found

### $useQuality

    $useQuality :

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

#### Type

#

## Tags

None found

### $compress

    $compress :

Compression level for PNG images.

#### Type

#

## Tags

None found

### $useCompress

    $useCompress :

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

#### Type

#

## Tags

None found

### $HTTPHeader

    $HTTPHeader :

Add HTTP headers for outputing image.

#### Type

#

## Tags

None found

### $bgColorDefault

    $bgColorDefault :

#### Type

#

## Tags

None found

### $bgColor

    $bgColor :

Background color to use, specified as part of options.

#### Type

#

## Tags

None found

### $saveFolder

    $saveFolder :

Where to save the target file.

#### Type

#

## Tags

None found

### $image

    $image :

The working image object.

#### Type

#

## Tags

None found

### $imageSrc

    $imageSrc :

Image filename, may include subdirectory, relative from $imageFolder

#### Type

#

## Tags

None found

### $pathToImage

    $pathToImage :

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

#### Type

#

## Tags

None found

### $fileType

    $fileType :

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

#### Type

#

## Tags

None found

### $extension

    $extension :

File extension to use when saving image.

#### Type

#

## Tags

None found

### $outputFormat

    $outputFormat :

Output format, supports null (image) or json.

#### Type

#

## Tags

None found

### $verbose

    $verbose :

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

#### Type

#

## Tags

None found

### $log

    $log :

Keep a log/trace on what happens

#### Type

#

## Tags

None found

### $palette

    $palette :

Handle image as palette image

#### Type

#

## Tags

None found

### $cacheFileName

    $cacheFileName :

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

#### Type

#

## Tags

None found

### $saveAs

    $saveAs :

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

#### Type

#

## Tags

None found

### $pngFilter

    $pngFilter :

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

#### Type

#

## Tags

None found

### $pngFilterCmd

    $pngFilterCmd :

#### Type

#

## Tags

None found

### $pngDeflate

    $pngDeflate :

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

#### Type

#

## Tags

None found

### $pngDeflateCmd

    $pngDeflateCmd :

#### Type

#

## Tags

None found

### $jpegOptimize

    $jpegOptimize :

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

#### Type

#

## Tags

None found

### $jpegOptimizeCmd

    $jpegOptimizeCmd :

#### Type

#

## Tags

None found

### $width

    $width :

Image dimensions, calculated from loaded image.

#### Type

#

## Tags

None found

### $height

    $height :

#### Type

#

## Tags

None found

### $newWidth

    $newWidth :

New image dimensions, incoming as argument or calculated.

#### Type

#

## Tags

None found

### $newWidthOrig

    $newWidthOrig :

#### Type

#

## Tags

None found

### $newHeight

    $newHeight :

#### Type

#

## Tags

None found

### $newHeightOrig

    $newHeightOrig :

#### Type

#

## Tags

None found

### $dpr

    $dpr :

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

#### Type

#

## Tags

None found

### $upscale

    $upscale :

#### Type

#

## Tags

None found

### $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

#

## Tags

None found

### $convolves

    $convolves :

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

#### Type

#

## Tags

None found

### $fillToFit

    $fillToFit :

Resize strategy to fill extra area with background color.

True or false.

#### Type

#

## Tags

None found

### $scale

    $scale :

To store value for option scale.

#### Type

#

## Tags

None found

### $rotateBefore

    $rotateBefore :

To store value for option.

#### Type

#

## Tags

None found

### $rotateAfter

    $rotateAfter :

To store value for option.

#### Type

#

## Tags

None found

### $autoRotate

    $autoRotate :

To store value for option.

#### Type

#

## Tags

None found

### $sharpen

    $sharpen :

To store value for option.

#### Type

#

## Tags

None found

### $emboss

    $emboss :

To store value for option.

#### Type

#

## Tags

None found

### $blur

    $blur :

To store value for option.

#### Type

#

## Tags

None found

### $offset

    $offset :

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

#### Type

#

## Tags

None found

### $fillWidth

    $fillWidth :

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

#### Type

#

## Tags

None found

### $fillHeight

    $fillHeight :

#### Type

#

## Tags

None found

### $allowRemote

    $allowRemote :

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

#### Type

#

## Tags

None found

### $remotePattern

    $remotePattern :

#### Type

#

## Tags

None found

### $useCache

    $useCache :

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

#### Type

#

## Tags

None found

### $remoteHostWhitelist

    $remoteHostWhitelist :

#### Type

#

## Tags

None found

### $verboseFileName

    $verboseFileName :

#### Type

#

## Tags

None found

### $asciiOptions

    $asciiOptions :

#### Type

#

## Tags

None found

### $copyStrategy

    $copyStrategy :

#### Type

#

## Tags

None found

### $cropWidth

    $cropWidth :

#### Type

#

## Tags

None found

### $cropHeight

    $cropHeight :

#### Type

#

## Tags

None found

### $attr

    $attr :

#### Type

#

## Tags

None found

## 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.

#

## Tags

None found

### 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

#

## Tags

None found

### setSaveFolder()

    setSaveFolder(string  $path) : $this

Set save folder, base folder for saving cache files.

#### Parameters

string | $path | where to store cached files.

#### Returns

$this

#

## Tags

todo | clean up how $this->saveFolder is used in other methods.

### useCache()

    useCache(boolean  $use = true) : $this

Use cache or not.

#### Parameters

boolean | $use | true or false to use cache.

#### Returns

$this

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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.

#

## Tags

None found

### 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

#

## Tags

None found

### 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.

#

## Tags

None found

### 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.

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### getTarget()

    getTarget() : Boolean|String

Get filename of target file.

#### Returns

Boolean|String —

as filename of target or false if not set.

#

## Tags

None found

### setOptions()

    setOptions(array  $args) : $this

Set options to use when processing image.

#### Parameters

array | $args | used when processing image.

#### Returns

$this

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### calculateNewWidthAndHeight()

    calculateNewWidthAndHeight() : $this

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

#### Returns

$this

#

## Tags

None found

### reCalculateDimensions()

    reCalculateDimensions() : $this

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

#### Returns

$this

#

## Tags

None found

### setSaveAsExtension()

    setSaveAsExtension(  $saveAs = null) : $this

Set extension for filename to save as.

#### Parameters

| $saveAs |

#### Returns

$this

#

## Tags

None found

### setJpegQuality()

    setJpegQuality(integer  $quality = null) : $this

Set JPEG quality to use when saving image

#### Parameters

integer | $quality | as the quality to set.

#### Returns

$this

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### preResize()

    preResize() : $this

Preprocess image before rezising it.

#### Returns

$this

#

## Tags

None found

### setCopyResizeStrategy()

    setCopyResizeStrategy(integer  $strategy) : $this

Resize or resample the image while resizing.

#### Parameters

integer | $strategy | as CImage::RESIZE or CImage::RESAMPLE

#### Returns

$this

#

## Tags

None found

### 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 |

#

## Tags

None found

### resize()

    resize() : $this

Resize and or crop the image.

#### Returns

$this

#

## Tags

None found

### postResize()

    postResize() : $this

Postprocess image after rezising image.

#### Returns

$this

#

## Tags

None found

### rotate()

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

Rotate image using angle.

#### Parameters

float | $angle | to rotate image.
| $bgColor |

#### Returns

$this

#

## Tags

None found

### rotateExif()

    rotateExif() : $this

Rotate image using information in EXIF.

#### Returns

$this

#

## Tags

None found

### trueColorToPalette()

    trueColorToPalette() : void

Convert true color image to palette image, keeping alpha.

http://stackoverflow.com/questions/5752514/how-to-convert-png-to-8-bit-png-using-php-gd-library

#

## Tags

None found

### sharpenImage()

    sharpenImage() : $this

Sharpen image using image convolution.

#### Returns

$this

#

## Tags

None found

### embossImage()

    embossImage() : $this

Emboss image using image convolution.

#### Returns

$this

#

## Tags

None found

### blurImage()

    blurImage() : $this

Blur image using image convolution.

#### Returns

$this

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### imageConvolution()

    imageConvolution(string  $options = null) : $this

Image convolution.

#### Parameters

string | $options | A string with 11 float separated by comma.

#### Returns

$this

#

## Tags

None found

### 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

#

## Tags

None found

### setPostProcessingOptions()

    setPostProcessingOptions(array  $options) : $this

Set optimizing and post-processing options.

#### Parameters

array | $options | with config for postprocessing with external tools.

#### Returns

$this

#

## Tags

None found

### 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.

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### 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.

#

## Tags

None found

### 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.

#

## Tags

None found

### 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.

#

## Tags

None found

### log()

    log(string  $message) : \this

Log an event if verbose mode.

#### Parameters

string | $message | to log.

#### Returns

\this

#

## Tags

None found

### setVerboseToFile()

    setVerboseToFile(string  $fileName) : void

Do verbose output to a file.

#### Parameters

string | $fileName | where to write the verbose output.

#

## Tags

None found

### getTargetImageExtension()

    getTargetImageExtension() : string

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

#### Returns

string —

as image extension.

#

## Tags

None found

### checkFileExtension()

    checkFileExtension(string  $extension) : $this

Check if file extension is valid as a file extension.

#### Parameters

string | $extension | of image file.

#### Returns

$this

#

## Tags

None found

### 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.

#

## Tags

None found

### 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

#

## Tags

None found

### 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

#

## Tags

None found

### colorsTotal()

    colorsTotal(resource  $im) : integer

Calculate number of colors in an image.

#### Parameters

resource | $im | the image.

#### Returns

integer

#

## Tags

None found

### 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.

#

## Tags

None found

### 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.

#

## Tags

None found

### verboseOutput()

    verboseOutput() : void

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

#

## Tags

None found

### 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

#

## Tags

None found

### CImage.php