PHP - .png and .gif together issue - php

I run a website where users can customize their own avatar. They can upload items, like "hats" and "shirts", which can be uploaded as a .png or .gif. Then, the "avatar" is outputted. The code for that is below. However when I "wear" an hat that is a .png, it shows up on my avatar, but if I wear a hat that is a .gif, it doesn't appear. How do I make it so that the avatar outputs .png items and .gif items together?
//retrieve user info from request
//example: Avatar.php?ID=1 (page will load avatar for user with ID of 1)
$ID = $db->real_escape_string(strip_tags(stripslashes($_GET['ID'])));
$Username = $db->real_escape_string(strip_tags(stripslashes($_GET['Username'])));
if (!$Username) {
$getUser = mysqli_query($db, "SELECT * FROM Users WHERE ID='".$ID."'");
}
else {
$getUser = mysqli_query($db, "SELECT * FROM Users WHERE Username='".$Username."'");
}
$gU = mysqli_fetch_object($getUser);
//load clothing
$Body = $gU->Body;
if (empty($Body)) {
$Body = "/Avatars/Avatar.png";
}
$Background = $gU->Background;
if (empty($Background)) {
$Background = "thingTransparent.png";
}
$Eyes = $gU->Eyes;
if (empty($Eyes)) {
$Eyes = "thingTransparent.png";
}
$Mouth = $gU->Mouth;
if (empty($Mouth)) {
$Mouth = "thingTransparent.png";
}
$Hair = $gU->Hair;
if (empty($Hair)) {
$Hair = "thingTransparent.png";
}
$Bottom = $gU->Bottom;
if (empty($Bottom)) {
$Bottom = "thingTransparent.png";
}
$Top = $gU->Top;
if (empty($Top)) {
$Top = "thingTransparent.png";
}
$TShirt = $gU->TShirt;
if (empty($TShirt)) {
$TShirt = "thingTransparent.png";
}
$Hat3 = $gU->Hat3;
if (empty($Hat3)) {
$Hat3 = "thingTransparent.png";
}
$Hat2 = $gU->Hat2;
if (empty($Hat2)) {
$Hat2 = "thingTransparent.png";
}
$Hat = $gU->Hat;
if (empty($Hat)) {
$Hat = "thingTransparent.png";
}
$Shoes = $gU->Shoes;
if (empty($Shoes)) {
$Shoes = "thingTransparent.png";
}
$Accessory = $gU->Accessory;
if (empty($Accessory)) {
$Accessory = "thingTransparent.png";
}
//render the avatar image
class StackImage
{
private $image;
private $width;
private $height;
public function __construct($Path)
{
if(!isset($Path) || !file_exists($Path))
return;
$this->image = imagecreatefrompng($Path);
imagesavealpha($this->image, true);
imagealphablending($this->image, true);
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
}
public function AddLayer($Path)
{
if(!isset($Path) || !file_exists($Path))
return;
$new = imagecreatefrompng($Path);
imagesavealpha($new, true);
imagealphablending($new, true);
imagecopy($this->image, $new, 0, 0, 0, 0, imagesx($new), imagesy($new));
}
public function Output($type = "image/png")
{
header("Content-Type: {$type}");
imagepng($this->image);
imagedestroy($this->image);
}
public function GetWidth()
{
return $this->width;
}
public function GetHeight()
{
return $this->height;
}
}
//add layer to image for the items that the user is wearing
//must be in specific order so you don't have unnecessary items overlapping each other incorrectly
//don't touch the bottom code
$Image = new StackImage("Store/Dir/thingTransparent.png");
$Image->AddLayer("Store/Dir/".$Background."");
$Image->AddLayer("Store/Dir/".$Body."");
$Image->AddLayer("Store/Dir/".$Eyes."");
$Image->AddLayer("Store/Dir/".$Mouth."");
$Image->AddLayer("Store/Dir/".$Bottom."");
$Image->AddLayer("Store/Dir/".$Top."");
$Image->AddLayer("Store/Dir/".$TShirt."");
$Image->AddLayer("Store/Dir/".$Hair."");
$Image->AddLayer("Store/Dir/".$Hat."");
$Image->AddLayer("Store/Dir/".$Shoes."");
$Image->AddLayer("Store/Dir/".$Accessory."");
//if the user is online, show online symbol
if (time() < $gU->expireTime) {
$Image->AddLayer("Images/Online.png");
}
//or else if the user is offline, show offline symbol
else {
$Image->AddLayer("Images/Offline.png");
}
//if the user is premium, show a little premium icon to the bottom left of their avatar
if ($gU->Premium == 1) {
$Image->AddLayer("Images/Premium.png");
}
//load up the rendered image
$Image->Output();

In AddLayer() you might need to change this line
$new = imagecreatefrompng($Path);
to check whether the source is GIF or PNG and then use the appropriate "imagecreatefrom*() method.

Related

Warning: imagecopy() expects parameter 1 to be resource, null given in /directory/avatar.php on line 72

Wassup fellow coders, i stumbled upon a weird error regarding my Image Layering php script for an avatar on a project i'm working on. Does any of you perhaps know the reason why its giving me an error like that? Because its the first time im seeing this error lol.
Here is the code btw:
<?php include "MISC/trueconnect.php";
if($_GET['id']){
$id = $_GET['id'];
$getUser = $conn->query("SELECT * FROM Users WHERE id='$id'");
} $avatar = $getUser->fetch(PDO::FETCH_OBJ);
$Body = $avatar->package;
if (empty($Body)) {
$Body = "Avatar";
}
$BottomID = $avatar->pants;
if (empty($BottomID)) {
$BottomID = "CharacterBG";
}
$ShirtID = $avatar->shirt;
if (empty($ShirtID)) {
$ShirtID = "CharacterBG";
}
$HatID = $avatar->hat;
if (empty($HatID)) {
$HatID = "CharacterBG";
}
$ToolID = $avatar->accessory;
if (empty($ToolID)) {
$ToolID = "CharacterBG";
}
$ScarfID = $avatar->mask;
if (empty($ScarfID)) {
$ScarfID = "CharacterBG";
}
$FaceID = $avatar->face;
if (empty($FaceID)) {
$ToolID = "CharacterBG";
}
class StackImage
{
private $image;
private $width;
private $height;
public function __construct($Path)
{
if(!isset($Path) || !file_exists($Path))
return;
$this->image = imagecreatefrompng($Path);
imagesavealpha($this->image, true);
imagealphablending($this->image, true);
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
}
public function AddLayer($Path)
{
if(!isset($Path) || !file_exists($Path))
return;
$new = imagecreatefrompng($Path);
imagesavealpha($new, true);
imagealphablending($new, true);
imagecopy($this->image, $new, 1, 0, 0, 0, imagesx($new), imagesy($new));
}
public function Output($type = "image/png")
{
header("Content-Type: {$type}");
imagepng($this->image);
imagedestroy($this->image);
}
public function GetWidth()
{
return $this->width;
}
public function GetHeight()
{
return $this->height;
}
}
$Image = new StackImage($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/CharacterBG.png");
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$Body);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$FaceID);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$BottomID);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$ShirtID);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$ScarfID);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$ToolID);
$Image->AddLayer($_SERVER["DOCUMENT_ROOT"]."/CDN/ITEMS/".$HatID);
$Image->Output();
?>
Thanks!
~Grizler
The error says it all. Parameter 1 doesn't get the resource parameter but get's null. Do you also think about why it could be null? You can use print_r($variable) to see if parameter 1 is actually null.

Fatal error Uncaught Error: Call to undefined method WP_Error

Error message
<b>Fatal error</b>: Uncaught Error: Call to undefined method WP_Error::resize() in C:\Users\User\Documents\xampp\htdocs\WordPress1\wp-content\themes\elina\framework\php\PeTheme\PeThemeImage.php:144
Stack trace:
#0 C:\Users\User\Documents\xampp\htdocs\WordPress1\wp-content\themes\elina\framework\php\PeTheme\PeThemeImage.php(282):
PeThemeImage->iresize('C:\\Users\\User\\D...', 320, 240, true)
#1 C:\Users\User\Documents\xampp\htdocs\WordPress1\wp-content\themes\elina\framework\php\PeTheme\PeThemeImage.php(364):
PeThemeImage->aq_resize('http://localhos...', 320, 240, true, false)
#2 C:\Users\User\Documents\xampp\htdocs\WordPress1\wp-content\themes\elina\framework\php\PeTheme\PeThemeImage.php(369): PeThemeImage->resize('http://localhos...', 320, 240, true)
from code
class PeThemeImage {
protected $basedir;
protected $baseurl;
protected $blanks = array();
protected $retina_enabled;
protected $lazyload_enabled;
protected $optkey;
public $generated;
protected $md5;
protected $image_sizes;
public function __construct() {
$wp_upload = wp_upload_dir();
$this->basedir = $wp_upload["basedir"];
$this->baseurl = $wp_upload["baseurl"];
$this->retina_enabled = peTheme()->options->get("retina") === "yes";
$this->lazyload_enabled = peTheme()->options->get("lazyImages") === "yes";
$this->optkey = "pe_theme_".PE_THEME_NAME."_thumbnails";
//delete_option($this->optkey);
$this->generated = get_option($this->optkey,array("index" => array()));
$this->md5 = md5(serialize($this->generated));
//peTheme()->thumbnail->clean();
}
public function &blank($w,$h) {
$key = "{$w}x{$h}";
if (isset($this->blanks[$key])) {
return $this->blanks[$key];
}
$external = "/img/blank/$key.gif";
if (file_exists(PE_THEME_PATH.$external)) {
// a blank img exists with the requested size
$this->blanks[$key] = PE_THEME_URL.$external;
} else {
// create blank img
$image = imagecreate($w, $h);
imagesavealpha($image, true);
imagecolortransparent($image, imagecolorallocatealpha($image, 0, 0, 0, 0));
ob_start();
imagegif($image);
$this->blanks[$key] = "data:image/gif;base64,".base64_encode(ob_get_clean());
imagedestroy($image);
}
return $this->blanks[$key];
}
public function placeholder($w,$h) {
return sprintf('<img src="%s" width="%s" height="%s" alt="" />',$this->blank($w,$h),$w,$h);
}
public function get_size($img) {
return stripos($img,"http") === 0 ? false : getimagesize($img);
}
public function is_url($url) {
return stripos($url,'http://') === 0 || strpos($url,'http://') === 0;
}
public function get_retina($url) {
$ret = $this->retina_enabled;
$lazy = $ret || $this->lazyload_enabled;
$common = sprintf('src="%s" alt=""',$url);
$img = str_replace(PE_THEME_URL,PE_THEME_PATH,$url);
if ($this->is_url($img)) {
$burl = $this->baseurl;
$bdir = $this->basedir;
$img = str_replace($burl,$bdir,$img);
if ($this->is_url($img)) {
// damn ... let's try adding/stripping www
if (stripos("://www.",$url) > -1) {
// www is there, try removing it
$burl = str_replace("://www.","://",$burl);
} else {
// no www, try adding it
$burl = str_replace("://","://www.",$burl);
}
$img = str_replace($burl,$bdir,$img);
}
}
if ($ret || $lazy) {
if ($ret) {
$ret = preg_replace("/\.(\w+)$/",'#2x.$1',$img);
$ret = is_readable($ret) ? preg_replace("/\.(\w+)$/",'#2x.$1',$url) : false;
}
if ($ret || $lazy) {
// try to get image size
$size = $this->get_size($img);
if ($size) {
list($w,$h) = $size;
$common = sprintf('src="%s" width="%s" height="%s" alt=""',$this->blank($w,$h),$w,$h);
} else {
$common = sprintf('src="%s" alt=""',$this->blank(1,1));
}
$lazy = sprintf(' data-original="%s"',$url);
$ret = $ret ? sprintf(' data-original-hires="%s"',$ret) : "";
}
} else {
$size = $this->get_size($img);
if ($size) {
list($w,$h) = $size;
$common = sprintf('src="%s" width="%s" height="%s" alt=""',$url,$w,$h);
}
}
return sprintf("<img %s%s%s>",$common,$lazy,$ret);
}
public function retina($img) {
echo $this->get_retina($img);
}
public function iresize($file,$width,$height,$crop) { // compatibilty wrapper for 3.4, >= 3.5 use wp_get_image_editor
if (function_exists("wp_get_image_editor")) {
// check if custom cropping defined
$size = "{$width}x{$height}";
$thumb = str_replace($this->basedir,"",preg_replace("/(\.\w+)$/","-$size\\1",$file));
if (!empty($this->generated["crop"][$thumb])) {
$crop = $this->generated["crop"][$thumb];
$url = str_replace($this->basedir,$this->baseurl,$file);
$this->crop($url,$crop,$width,$height);
return $this->basedir.$thumb;
}
// WP 3.5
$editor = wp_get_image_editor($file);
$editor->resize($width,$height,$crop);
$dest_file = $editor->generate_filename();
$editor->save($dest_file);
return $dest_file;
} else {
$f = "image_resize"; // compatibilty with WP 3.4 and below
return $f($file,$width,$height,$crop);
}
}
public static function makeBWimage($file,$dest) {
//$image = wp_load_image($file);
$image = imagecreatefromstring( file_get_contents( $file ) );
$res = imagefilter($image,IMG_FILTER_GRAYSCALE);
$res = $res && imagejpeg($image,$dest);
imagedestroy($image);
return $res;
}
public function blackwhite_filter($meta) {
if (!isset($meta) || !is_array($meta) || count($meta) == 0) {
return $meta;
}
$base = dirname($this->basedir."/".$meta["file"]);
$thumbs = array_keys(PeGlobal::$config["image-sizes"]);
if (isset($meta["sizes"])) {
$sizes =& $meta["sizes"];
}
foreach ($thumbs as $thumb) {
if (substr($thumb,-3,3) == "-bw") {
$normal = substr($thumb,0,strlen($thumb)-3);
if (isset($sizes) && isset($sizes[$normal])) {
$bwthumb = array_merge($sizes[$normal]);
} else {
$bwthumb = array("file" => wp_basename($meta["file"]), "width" => $meta["width"], "height" => $meta["height"]);
}
$file = "$base/{$bwthumb['file']}";
$dest = preg_replace('/\.\w+$/', "-bw.jpg", $file);
if (!isset($seen[$file])) {
$seen[$file] = true;
$this->makeBWimage($file,$dest);
}
$bwthumb["file"] = wp_basename($dest);
$meta["sizes"][$thumb] = $bwthumb;
}
}
return $meta;
}
/**
* Title : Aqua Resizer
* Description : Resizes WordPress images on the fly
* Version : 1.1.3
* Author : Syamil MJ
* Author URI : http://aquagraphite.com
* License : WTFPL - http://sam.zoy.org/wtfpl/
* Documentation : https://github.com/sy4mil/Aqua-Resizer/
*
* #param string $url - (required) must be uploaded using wp media uploader
* #param int $width - (required)
* #param int $height - (optional)
* #param bool $crop - (optional) default to soft crop
* #param bool $single - (optional) returns an array if false
* #uses wp_upload_dir()
*
* #return str|array
*/
public function aq_resize( $url, $width, $height = null, $crop = null, $single = true ) {
//validate inputs
if(!$url OR !$width ) return false;
//define upload path & dir
$upload_dir = $this->basedir;
$upload_url = $this->baseurl;
//check if $img_url is local
//if(strpos( $url, home_url() ) === false) return false;
if(strpos( $url, $upload_url ) === false) return false;
//define path of image
$rel_path = str_replace( $upload_url, '', $url);
$img_path = $upload_dir . $rel_path;
//check if img path exists, and is an image indeed
if( !file_exists($img_path) OR !getimagesize($img_path) ) return false;
//get image info
$info = pathinfo($img_path);
$ext = $info['extension'];
list($orig_w,$orig_h) = getimagesize($img_path);
//get image size after cropping
$dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
$dst_w = $dims[4];
$dst_h = $dims[5];
//use this to check if cropped image already exists, so we can return that instead
$suffix = "{$dst_w}x{$dst_h}";
$dst_rel_path = str_replace( '.'.$ext, '', $rel_path);
$destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
//if orig size is smaller
if($width >= $orig_w) {
if(!$dst_h) :
//can't resize, so return original url
$img_url = $url;
$dst_w = $orig_w;
$dst_h = $orig_h;
else :
//else check if cache exists
if(file_exists($destfilename) && getimagesize($destfilename)) {
$img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
}
//else resize and return the new resized image url
else {
$resized_img_path = $this->iresize( $img_path, $width, $height, $crop );
$resized_rel_path = str_replace( $upload_dir, '', $resized_img_path);
$img_url = $upload_url . $resized_rel_path;
}
endif;
}
//else check if cache exists
elseif(file_exists($destfilename) && getimagesize($destfilename)) {
$img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
}
//else, we resize the image and return the new resized image url
else {
$resized_img_path = $this->iresize( $img_path, $width, $height, $crop );
$resized_rel_path = str_replace( $upload_dir, '', $resized_img_path);
$img_url = $upload_url . $resized_rel_path;
}
//return the output
if($single) {
//str return
$image = $img_url;
} else {
//array return
$image = array (
0 => $img_url,
1 => $dst_w,
2 => $dst_h
);
}
$this->bwMode = false;
if ($url != $img_url && !is_admin()) {
$size = "{$dst_w}x{$dst_h}";
if (!isset($this->generated["index"][$rel_path][$size])) {
$this->generated["index"][$rel_path][$size] = true;
}
}
return $image;
}
public function file($url) {
if(strpos($url,$this->baseurl) === false) return false;
return str_replace($this->baseurl, $this->basedir, $url);
}
public function crop($url,$crop,$w,$h) {
if (($file = $this->file($url)) === false) return false;
$file = str_replace($this->baseurl, $this->basedir, $url);
$size = "{$w}x{$h}";
$thumb = preg_replace("/(\.\w+)$/","-$size\\1",$file);
list($x1,$y1,$x2,$y2) = explode(",",$crop);
$cw = $x2-$x1;
if ($cw<$w) {
// fix x1
$x1 -= min($x1,$w-$cw);
$cw = $x2-$x1;
if ($cw < $w) {
// fix x2
$x2 += $w-$cw;
}
}
$y2 = $y1 + ceil($h*($cw/$w));
$ch = $y2-$y1;
if ($ch<$h) {
// fix y1
$y1 -= min($y1,$h-$ch);
$ch = $y2-$y1;
if ($ch < $h) {
// fix y2
$y2 += $h-$ch;
}
}
$cw = $x2-$x1;
$ch = $y2-$y1;
$editor = wp_get_image_editor($file);
$editor->crop($x1,$y1,$cw,$ch,$w,$h);
$ret = $editor->save($thumb);
if (!empty($ret["path"])) {
$ret["url"] = str_replace($this->basedir,$this->baseurl,$ret["path"]);
$ret["cburl"] = $ret["url"]."?t=".filemtime($ret["path"]);
}
$editor = null;
return $ret;
}
public function resize($url,$w,$h = null,$crop = true) {
return $this->aq_resize($url,$w,$h,$crop,false);
}
public function resizedImg($url,$w,$h = null,$crop = true) {
if (!$url) return;
$result = $this->resize($url,$w,$h,$crop);
if (!$result) return;
$unscaled = $url;
list($url,$w,$h) = $result;
return apply_filters("pe_theme_resized_img","<img alt=\"\" width=\"$w\" height=\"$h\" src=\"$url\"/>",$url,$w,$h,$unscaled);
}
public function resizedImgUrl($url,$w,$h = null,$crop = true) {
return $this->aq_resize($url,$w,$h,$crop,true);
}
public function stats() {
if ($this->md5 != md5(serialize($this->generated))) {
update_option($this->optkey,$this->generated);
}
}
public function get_images_size() {
// make thumbnails and other intermediate sizes
global $_wp_additional_image_sizes;
$this->image_sizes = array();
foreach ( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
$sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
else
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
$sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
else
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
$sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
else
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$this->image_sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
}
public function post_thumbnail_html_filter($html,$post_id,$post_thumbnail_id,$size,$attr,$retina = false,$lazy = false) {
//return $html;
if (empty($post_thumbnail_id)) return $html;
$url = wp_get_attachment_url($post_thumbnail_id);
if (empty($url)) return $html;
if (!isset($this->image_sizes[$size])) {
$this->get_images_size();
if (!isset($this->image_sizes[$size])) {
return $html;
}
}
$size = (object) $this->image_sizes[$size];
if (!empty($size->width) && !empty($size->height)) {
$resized = $this->resize($url,$size->width,$size->height,empty($size->crop) ? false : true);
if (empty($resized)) {
return $html;
}
}
list($img,$w,$h) = $resized;
if ($retina || $lazy) {
$blank = $this->blank($w,$h);
if ($retina) {
$lazy = true;
$retina = $this->resizedImgUrl($url,$w*2,$h*2);
$newsrc = sprintf('src="%s" data-original="%s" data-original-hires="%s"',$blank,$img,$retina);
} else {
$newsrc = sprintf('src="%s" data-original="%s"',$blank,$img);
}
} else {
$newsrc = sprintf('src="%s"',$img);
}
$newwidth = sprintf('width="%s"',$w);
$newheight = sprintf('height="%s"',$h);
$html = preg_replace("/src=\"[^\"]+\"/",$newsrc,$html);
$html = preg_replace("/width=\"\d+\"/",$newwidth,$html);
$html = preg_replace("/height=\"\d+\"/",$newheight,$html);
if ($lazy) {
if (strpos($html,'class=') > -1) {
$html = preg_replace("/class=\"/",'class="peLazyLoading ',$html);
} else {
$html = preg_replace("/<img /",'<img class="peLazyLoading" ',$html);
}
}
return $html;
}
public function bw($url) {
if(!$url) return "";
//define upload path & dir
$upload_dir = $this->basedir;
$upload_url = $this->baseurl;
//check if $img_url is local
if(strpos( $url, $upload_url ) === false) return false;
//define path of image
$rel_path = str_replace( $upload_url, '', $url);
$img_path = $upload_dir . $rel_path;
//check if img path exists, and is an image indeed
if( !file_exists($img_path) OR !getimagesize($img_path) ) return "";
//get image info
$info = pathinfo($img_path);
$ext = $info['extension'];
$dst_rel_path = str_replace( '.'.$ext, '', $rel_path);
$destfilename = "{$upload_dir}{$dst_rel_path}-bw.jpg";
if (file_exists($destfilename) && getimagesize($destfilename)) {
$url = "{$upload_url}{$dst_rel_path}-bw.jpg";
} else {
try {
if (#$this->makeBWimage($img_path,$destfilename)) {
$url = "{$upload_url}{$dst_rel_path}-bw.jpg";
}
} catch(Exception $e) {
}
}
return $url;
}
}
I believe the problem is with this line(#140 I think):
$editor = wp_get_image_editor($file);
As per the documentation, wp_get_image_editor() would return WP_Error if there's any problem.
So what you can do is, try adding a condition to check whether the $editor returned is a WP_Error or not. If not, do the resizing(because it would be an instance of WP_Image_Editor that would be returned if successful).
Eg:
$editor = wp_get_image_editor($file);
if( ! is_wp_error( $editor ) ) {
$editor->resize($width,$height,$crop);
$dest_file = $editor->generate_filename();
$editor->save($dest_file);
return $dest_file;
}
else
{
return $file;
}

Cropping an image using php

I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.

Delay a while loop in PHP to prevent memory exhaustion?

I have a pretty simple image resize script that loops through 1000 folders, with different amounts of images in each folder. On my testing server, there aren't a lot of images, so it runs fine...but live with about 100K images...it will run into the memory problem. The php memory is already set to 384M, but i'd rather have the script maybe only process 10 folders at a time, stop for a bit, then start again. How can I do that within the while loop? use the sleep function maybe?
Here it is...
class DevTestHelper {
//This will Go through all full size images and resize images into requested folder
function resizeGalleryImages($destFolder, $width, $height, $isCrop = false) {
$count = 1000;
$source = JPATH_SITE."/images/gallery/full";
$dest = JPATH_SITE."/images/gallery/".$destFolder;
echo 'Processing Images<br>';
//Loop through all 1000 folders 0 to 999 in the /full dir
for($i=0; $i < $count;$i++) {
$iPath = $source.'/'.$i;
if(is_dir($iPath)) {
$h = opendir($iPath);
//Loop through all the files in numbered folder
while ($entry = readdir($h)) {
//only read files
if ($entry != "." && $entry != ".." && !is_dir($entry)) {
$img = new GImage($source.'/'.$i.'/'.$entry);
$tmp = $img->resize($width, $height, true, 3);
if($isCrop) {
$tmpWidth = $tmp->getWidth();
$tmpHeight = $tmp->getHeight();
$xOffset = ($tmpWidth - $width) / 2;
$yOffset = ($tmpHeight - $height) / 2;
$tmp->crop($width, $height, $xOffset, $yOffset, false, 3);
}
$destination = $dest.'/'.$i.'/'.$entry;
if(!$tmp->toFile($destination)) {
echo 'error in creating resized image at: '.$destination.'<br>';
}
flush();
ob_flush();
sleep(10);
echo $entry ;
//echo $entry.'<br>';
}
}
echo 'Processed: '.$i.' Folder<br>';
}
}
Thanks for any suggestions.
/**
* Class to manipulate an image.
*
* #package Gallery.Libraries
* #subpackage Media
* #version 1.0
*/
class GImage extends JObject
{
/**
* The image handle
*
* #access private
* #var resource
*/
var $_handle = null;
/**
* The source image path
*
* #access private
* #var string
*/
var $_path = null;
var $_support = array();
/**
* Constructor
*
* #access public
* #return void
* #since 1.0
*/
function __construct($source=null)
{
// First we test if dependencies are met.
if (!GImageHelper::test()) {
$this->setError('Unmet Dependencies');
return false;
}
// Determine which image types are supported by GD.
$info = gd_info();
if ($info['JPG Support']) {
$this->_support['JPG'] = true;
}
if ($info['GIF Create Support']) {
$this->_support['GIF'] = true;
}
if ($info['PNG Support']) {
$this->_support['PNG'] = true;
}
// If the source input is a resource, set it as the image handle.
if ((is_resource($source) && get_resource_type($source) == 'gd')) {
$this->_handle = &$source;
} elseif (!empty($source) && is_string($source)) {
// If the source input is not empty, assume it is a path and populate the image handle.
//Andy - Big freaking cockroach: if file is wrong type or doesn't even exist the error is not handled.
$this->loadFromFile($source);
}
}
function crop($width, $height, $left, $top, $createNew = true, $scaleMethod = JXIMAGE_SCALE_INSIDE)
{
// Make sure the file handle is valid.
if ((!is_resource($this->_handle) || get_resource_type($this->_handle) != 'gd')) {
$this->setError('Invalid File Handle');
return false;
}
// Sanitize width.
$width = ($width === null) ? $height : $width;
if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $width)) {
$width = intval(round($this->getWidth() * floatval(str_replace('%', '', $width)) / 100));
} else {
$width = intval(round(floatval($width)));
}
// Sanitize height.
$height = ($height === null) ? $width : $height;
if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $height)) {
$height = intval(round($this->getHeight() * floatval(str_replace('%', '', $height)) / 100));
} else {
$height = intval(round(floatval($height)));
}
// Sanitize left.
$left = intval(round(floatval($left)));
// Sanitize top.
$top = intval(round(floatval($top)));
// Create the new truecolor image handle.
$handle = imagecreatetruecolor($width, $height);
// Allow transparency for the new image handle.
imagealphablending($handle, false);
imagesavealpha($handle, true);
if ($this->isTransparent()) {
// Get the transparent color values for the current image.
$rgba = imageColorsForIndex($this->_handle, imagecolortransparent($this->_handle));
$color = imageColorAllocate($this->_handle, $rgba['red'], $rgba['green'], $rgba['blue']);
// Set the transparent color values for the new image.
imagecolortransparent($handle, $color);
imagefill($handle, 0, 0, $color);
imagecopyresized(
$handle,
$this->_handle,
0, 0,
$left,
$top,
$width,
$height,
$width,
$height
);
} else {
imagecopyresampled(
$handle,
$this->_handle,
0, 0,
$left,
$top,
$width,
$height,
$width,
$height
);
}
// If we are cropping to a new image, create a new GImage object.
if ($createNew)
{
// Create the new GImage object for the new truecolor image handle.
$new = new GImage($handle);
return $new;
} else
{
// Swap out the current handle for the new image handle.
$this->_handle = &$handle;
return true;
}
}
function filter($type)
{
// Initialize variables.
$name = preg_replace('#[^A-Z0-9_]#i', '', $type);
$className = 'GImageFilter_'.ucfirst($name);
if (!class_exists($className))
{
jimport('joomla.filesystem.path');
if ($path = JPath::find(GImageFilter::addIncludePath(), strtolower($name).'.php'))
{
require_once $path;
if (!class_exists($className)) {
$this->setError($className.' not found in file.');
return false;
}
}
else {
$this->setError($className.' not supported. File not found.');
return false;
}
}
$instance = new $className;
if (is_callable(array($instance, 'execute')))
{
// Setup the arguments to call the filter execute method.
$args = func_get_args();
array_shift($args);
array_unshift($args, $this->_handle);
// Call the filter execute method.
$return = call_user_func_array(array($instance, 'execute'), $args);
// If the filter failed, proxy the error and return false.
if (!$return) {
$this->setError($instance->getError());
return false;
}
return true;
}
else {
$this->setError($className.' not valid.');
return false;
}
}
function getHeight()
{
return imagesy($this->_handle);
}
function getWidth()
{
return imagesx($this->_handle);
}
function isTransparent()
{
// Make sure the file handle is valid.
if ((!is_resource($this->_handle) || get_resource_type($this->_handle) != 'gd')) {
$this->setError('Invalid File Handle');
return false;
}
return (imagecolortransparent($this->_handle) >= 0);
}
function loadFromFile($path)
{
// Make sure the file exists.
if (!JFile::exists($path)) {
$this->setError('File Does Not Exist');
return false;
}
// Get the image properties.
$properties = GImageHelper::getProperties($path);
if (!$properties) {
return false;
}
// Attempt to load the image based on the MIME-Type
switch ($properties->get('mime'))
{
case 'image/gif':
// Make sure the image type is supported.
if (empty($this->_support['GIF'])) {
$this->setError('File Type Not Supported');
return false;
}
// Attempt to create the image handle.
$handle = #imagecreatefromgif($path);
if (!is_resource($handle)) {
$this->setError('Unable To Process Image');
return false;
}
$this->_handle = &$handle;
break;
case 'image/jpeg':
// Make sure the image type is supported.
if (empty($this->_support['JPG'])) {
$this->setError('File Type Not Supported');
return false;
}
// Attempt to create the image handle.
$handle = #imagecreatefromjpeg($path);
if (!is_resource($handle)) {
$this->setError('Unable To Process Image');
return false;
}
$this->_handle = &$handle;
break;
case 'image/png':
// Make sure the image type is supported.
if (empty($this->_support['PNG'])) {
$this->setError('File Type Not Supported');
return false;
}
// Attempt to create the image handle.
$handle = #imagecreatefrompng($path);
if (!is_resource($handle)) {
$this->setError('Unable To Process Image');
return false;
}
$this->_handle = &$handle;
break;
default:
$this->setError('File Type Not Supported');
return false;
break;
}
// Set the filesystem path to the source image.
$this->_path = $path;
return true;
}
function resize($width, $height, $createNew = true, $scaleMethod = JXIMAGE_SCALE_INSIDE)
{
// Make sure the file handle is valid.
if ((!is_resource($this->_handle) || get_resource_type($this->_handle) != 'gd')) {
$this->setError('Invalid File Handle');
return false;
}
// Prepare the dimensions for the resize operation.
$dimensions = $this->_prepareDimensions($width, $height, $scaleMethod);
if (empty($dimensions)) {
return false;
}
//var_dump($dimensions);
// Create the new truecolor image handle.
$handle = imagecreatetruecolor($dimensions['width'], $dimensions['height']);
// Allow transparency for the new image handle.
imagealphablending($handle, false);
imagesavealpha($handle, true);
if ($this->isTransparent()) {
// Get the transparent color values for the current image.
$rgba = imageColorsForIndex($this->_handle, imagecolortransparent($this->_handle));
$color = imageColorAllocate($this->_handle, $rgba['red'], $rgba['green'], $rgba['blue']);
// Set the transparent color values for the new image.
imagecolortransparent($handle, $color);
imagefill($handle, 0, 0, $color);
imagecopyresized(
$handle,
$this->_handle,
0, 0, 0, 0,
$dimensions['width'],
$dimensions['height'],
$this->getWidth(),
$this->getHeight()
);
} else {
imagecopyresampled(
$handle,
$this->_handle,
0, 0, 0, 0,
$dimensions['width'],
$dimensions['height'],
$this->getWidth(),
$this->getHeight()
);
}
// If we are resizing to a new image, create a new GImage object.
if ($createNew)
{
// Create the new GImage object for the new truecolor image handle.
$new = new GImage($handle);
return $new;
} else
{
// Swap out the current handle for the new image handle.
$this->_handle = &$handle;
return true;
}
}
function toFile($path, $type = IMAGETYPE_JPEG, $options=array())
{
switch ($type)
{
case IMAGETYPE_GIF:
$ret = imagegif($this->_handle, $path);
break;
case IMAGETYPE_PNG:
$ret = imagepng($this->_handle, $path, (array_key_exists('quality', $options)) ? $options['quality'] : 0);
break;
case IMAGETYPE_JPEG:
default:
$ret = imagejpeg($this->_handle, $path, (array_key_exists('quality', $options)) ? $options['quality'] : 100);
break;
}
return $ret;
}
function display() {
//header('Content-type: image/jpeg');
imagejpeg($this->_handle,'',100);
}
function _prepareDimensions($width, $height, $scaleMethod)
{
// Sanitize width.
$width = ($width === null) ? $height : $width;
if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $width)) {
$width = intval(round($this->getWidth() * floatval(str_replace('%', '', $width)) / 100));
} else {
$width = intval(round(floatval($width)));
}
// Sanitize height.
$height = ($height === null) ? $width : $height;
if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $height)) {
$height = intval(round($this->getHeight() * floatval(str_replace('%', '', $height)) / 100));
} else {
$height = intval(round(floatval($height)));
}
$dimensions = array();
if ($scaleMethod == JXIMAGE_SCALE_FILL)
{
$dimensions['width'] = $width;
$dimensions['height'] = $height;
}
elseif ($scaleMethod == JXIMAGE_SCALE_INSIDE || $scaleMethod == JXIMAGE_SCALE_OUTSIDE)
{
$rx = $this->getWidth() / $width;
$ry = $this->getHeight() / $height;
if ($scaleMethod == JXIMAGE_SCALE_INSIDE)
$ratio = ($rx > $ry) ? $rx : $ry;
else
$ratio = ($rx < $ry) ? $rx : $ry;
$dimensions['width'] = round($this->getWidth() / $ratio);
$dimensions['height'] = round($this->getHeight() / $ratio);
}
else {
$this->setError('Invalid Fit Option');
return false;
}
return $dimensions;
}
}
class GImageFilter extends JObject
{
/**
* Add a directory where GImage should search for filters. You may
* either pass a string or an array of directories.
*
* #access public
* #param string A path to search.
* #return array An array with directory elements
* #since 1.5
*/
function addIncludePath($path='')
{
static $paths;
if (!isset($paths)) {
$paths = array(dirname(__FILE__).'/image');
}
// force path to array
settype($path, 'array');
// loop through the path directories
foreach ($path as $dir)
{
if (!empty($dir) && !in_array($dir, $paths)) {
array_unshift($paths, JPath::clean( $dir ));
}
}
return $paths;
}
function execute()
{
$this->setError('Method Not Implemented');
return false;
}
}
class GImageHelper
{
function getProperties($path)
{
// Initialize the path variable.
$path = (empty($path)) ? $this->_path : $path;
// Make sure the file exists.
if (!JFile::exists($path)) {
$e = new JException('File Does Not Exist');
return false;
}
// Get the image file information.
$info = #getimagesize($path);
if (!$info) {
$e = new JException('Unable To Get Image Size');
return false;
}
// Build the response object.
$result = new JObject;
$result->set('width', $info[0]);
$result->set('height', $info[1]);
$result->set('type', $info[2]);
$result->set('attributes', $info[3]);
$result->set('bits', #$info['bits']);
$result->set('channels', #$info['channels']);
$result->set('mime', $info['mime']);
return $result;
}
function test()
{
return (function_exists('gd_info') && function_exists('imagecreatetruecolor'));
}
}
It looks to me like you have a memory leak, when creating $img using new GImage it will likely be reading the image into memory which you never release.
You take a copy of the resized image:
$tmp = $img->resize($width, $height, true, 3);
but next time around the loop you create a new GImage again using the $img variable.
Does GIMage have some kind of close or cleanup function? If so, do that at the end of each loop before you call new GImage again.
closeGImage($img);
UPDATE:
In response to your updated question it looks like you can do one of two things:
Change the 3rd parameter of $img->resize() to false as this will stop a new GImage being created on image resize.
Write your own image destroy function as part of the GImage class. Because GImage is based upon the GD library you can use the imagedestroy function, see here.
UPDATE 2:
Ok, so following on from your comment... What you'll want to do to create a destroy image function is inside the GImage class, add the following function:
function closeImage()
{
imagedestroy($this->_handle);
}
Now at the bottom of the for loop in devtest.php add a call to this function:
...
ob_flush();
sleep(10);
echo $entry ;
$img->closeImage();
...
Try using sleep or usleep to avoid CPU overload.
Maybe GImage have a dispose() or destroy() method to avoid memory retention.
You could also do batch processing.

PHP: Resize/making thumbnails?

Helo i now have finish making my upload profilephoto system. Now i want include creating thumbnails of the uploaded image in different sizes eg 48x48 and 148x50, how can i do this?
Example / good tutorials for this?
You will need to use PHP's GD library or ImageMagick library.
First find out which, if any, you have installed on your development and production environments.
Then start looking for tutorials depending on which one you want to use. There are many out there.
GD usually comes pre-packed with PHP5.
Back then I used imagemagick.
$ convert -resize 48x48 xyz.jpg xyz_48x48.jpg
It is also available as a php module: http://php.net/manual/en/book.imagick.php
But I haven't used that one, but I suppose it knows exactly the same as the command line variant.
Tutorial with imagecreatefrom()... , imagecopyresized(), imagejpeg()
Here my class for resizing. Replace the 150 occurences with a variable.
<?php
/**
* Takes an image and creates a thumbnail of it.
*/
class ImageThumbnail
{
private $thumbnail;
/**
* Create a new object
*
* #param string $source Location of the original image (can be null if set using create())
* #param string $extension File extension, if it has been obfuscated (e.g. moved to PHP's tmp dir)
*/
public function __construct($source, $extension)
{
if ($source)
{
$this->create($source, $extension);
}
}
public function create($source, $extension = null)
{
if (!$extension)
{
$parts = explode('.', $source); // get the file extension
$extension = array_pop($parts);
}
else
{
$extension = ltrim($extension, '.'); // get rid of any prefixing dots
}
// Get the images size
$size = getImageSize($source);
// Width > height
if ($size[0] > $size[1])
{
$width = 150;
$height = (int) (150 * $size[1] / $size[0]);
}
// Height > width
else
{
$width = (int) (150 * $size[0] / $size[1]);
$height = 150;
}
$readFunc = 'imageCreateFrom'.filenameToImageMime($source);
if (!$source = $readFunc($source))
{
throw new Exception('The source image is unreadable');
}
// Create an blank image for the thumbnail
$thumbnail = imageCreateTrueColor($width, $height);
// Copy source image onto new image
imageCopyResized($thumbnail, $source, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
$this->thumbnail = $thumbnail;
}
public function getThumbnail()
{
return $this->thumbnail;
}
public function move($target)
{
$func = 'image'.filenameToImageMime($target);
$func($this->thumbnail, $target);
imageDestroy($this->thumbnail);
}
}
function makenicepic($srcfile,$tofile,$maxwidth,$maxheight) {
//global $_SGLOBAL;
// check file exist
if (!file_exists($srcfile)) {
return '';
}
$dstfile = $tofile;
include_once(S_ROOT.'./data/data_setting.php');
// //size
$tow = $maxwidth;
$toh =$maxheight;
$make_max = 0;
$maxtow = 950;
$maxtoh = 700;
$make_max = 1;
$im = '';
if($data = getimagesize($srcfile)) {
if($data[2] == 1) {
$make_max = 0;//gif skip
if(function_exists("imagecreatefromgif")) {
$im = imagecreatefromgif($srcfile);
}
} elseif($data[2] == 2) {
if(function_exists("imagecreatefromjpeg")) {
$im = imagecreatefromjpeg($srcfile);
}
} elseif($data[2] == 3) {
if(function_exists("imagecreatefrompng")) {
$im = imagecreatefrompng($srcfile);
}
}
}
if(!$im) return '';
$srcw = imagesx($im);
$srch = imagesy($im);
$towh = $tow/$toh;
$srcwh = $srcw/$srch;
if($towh <= $srcwh){
$ftow = $tow;
$ftoh = $ftow*($srch/$srcw);
$fmaxtow = $maxtow;
$fmaxtoh = $fmaxtow*($srch/$srcw);
} else {
$ftoh = $toh;
$ftow = $ftoh*($srcw/$srch);
$fmaxtoh = $maxtoh;
$fmaxtow = $fmaxtoh*($srcw/$srch);
}
if($srcw <= $maxtow && $srch <= $maxtoh) {
$make_max = 0;
}
if($srcw > $tow || $srch > $toh) {
if(function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && #$ni = imagecreatetruecolor($ftow, $ftoh)) {
imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
if($make_max && #$maxni = imagecreatetruecolor($fmaxtow, $fmaxtoh)) {
imagecopyresampled($maxni, $im, 0, 0, 0, 0, $fmaxtow, $fmaxtoh, $srcw, $srch);
}
} elseif(function_exists("imagecreate") && function_exists("imagecopyresized") && #$ni = imagecreate($ftow, $ftoh)) {
imagecopyresized($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
if($make_max && #$maxni = imagecreate($fmaxtow, $fmaxtoh)) {
imagecopyresized($maxni, $im, 0, 0, 0, 0, $fmaxtow, $fmaxtoh, $srcw, $srch);
}
} else {
return '';
}
if(function_exists('imagejpeg')) {
imagejpeg($ni, $dstfile);
//big pic
if($make_max) {
imagejpeg($maxni, $srcfile);
}
} elseif(function_exists('imagepng')) {
imagepng($ni, $dstfile);
if($make_max) {
imagepng($maxni, $srcfile);
}
}
imagedestroy($ni);
if($make_max) {
imagedestroy($maxni);
}
}
imagedestroy($im);
if(!file_exists($dstfile)) {
return '';
} else {
return $dstfile;
}
}

Categories