Error: Class 'Object' not found in Cakephp - php

I have this component in my app:
<?php
class ImageComponent extends Object {
var $name = 'Image';
private $file;
private $image;
private $info;
public function prepare($file) {
if (file_exists($file)) {
$this->file = $file;
$info = getimagesize($file);
$this->info = array(
'width' => $info[0],
'height' => $info[1],
'bits' => $info['bits'],
'mime' => $info['mime']
);
$this->image = $this->create($file);
} else {
exit('Error: Could not load image ' . $file . '!');
}
}
public function create($image) {
$mime = $this->info['mime'];
if ($mime == 'image/gif') {
return imagecreatefromgif($image);
} elseif ($mime == 'image/png') {
return imagecreatefrompng($image);
} elseif ($mime == 'image/jpeg') {
return imagecreatefromjpeg($image);
}
}
public function save($file, $quality = 100) {
$info = pathinfo($file);
$extension = strtolower($info['extension']);
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($this->image, $file, $quality);
} elseif($extension == 'png') {
imagepng($this->image, $file, 0);
} elseif($extension == 'gif') {
imagegif($this->image, $file);
}
imagedestroy($this->image);
}
public function resize($width = 0, $height = 0,$r=255,$g=255,$b=255,$ratio=true) {
if (!$this->info['width'] || !$this->info['height']) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = min($width / $this->info['width'], $height / $this->info['height']);
if ($scale == 1) {
return;
}
if($ratio!=false)
{
$new_width = (int)($this->info['width'] * $scale);
$new_height = (int)($this->info['height'] * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, $r, $g, $b, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, $r, $g, $b);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $width;
$this->info['height'] = $height;
}
else
{
$new_width = (int)($width);
$new_height = (int)($height);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, $r, $g, $b, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, $r, $g, $b);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $width;
$this->info['height'] = $height;
}
}
public function watermark($file, $position = 'bottomright') {
$watermark = $this->create($file);
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
switch($position) {
case 'topleft':
$watermark_pos_x = 0;
$watermark_pos_y = 0;
break;
case 'topright':
$watermark_pos_x = $this->info['width'] - $watermark_width;
$watermark_pos_y = 0;
break;
case 'bottomleft':
$watermark_pos_x = 0;
$watermark_pos_y = $this->info['height'] - $watermark_height;
break;
case 'bottomright':
$watermark_pos_x = $this->info['width'] - $watermark_width;
$watermark_pos_y = $this->info['height'] - $watermark_height;
break;
}
imagecopy($this->image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0, 120, 40);
imagedestroy($watermark);
}
public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
$image_old = $this->image;
$this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y);
imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $bottom_x - $top_x;
$this->info['height'] = $bottom_y - $top_y;
}
public function rotate($degree, $color = 'FFFFFF') {
$rgb = $this->html2rgb($color);
$this->image = imagerotate($this->image, $degree, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
$this->info['width'] = imagesx($this->image);
$this->info['height'] = imagesy($this->image);
}
private function filter($filter) {
imagefilter($this->image, $filter);
}
private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') {
$rgb = $this->html2rgb($color);
imagestring($this->image, $size, $x, $y, $text, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
}
private function merge($file, $x = 0, $y = 0, $opacity = 100) {
$merge = $this->create($file);
$merge_width = imagesx($image);
$merge_height = imagesy($image);
imagecopymerge($this->image, $merge, $x, $y, 0, 0, $merge_width, $merge_height, $opacity);
}
private function html2rgb($color) {
if ($color[0] == '#') {
$color = substr($color, 1);
}
if (strlen($color) == 6) {
list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
} elseif (strlen($color) == 3) {
list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
} else {
return FALSE;
}
$r = hexdec($r);
$g = hexdec($g);
$b = hexdec($b);
return array($r, $g, $b);
}
public function roundcorner($sourceImageFile, $outputfile,$radius='8') {
# test source image
if (file_exists($sourceImageFile)) {
$res = is_array($info = getimagesize($sourceImageFile));
}
else $res = false;
# open image
if ($res) {
$w = $info[0];
$h = $info[1];
switch ($info['mime']) {
case 'image/jpeg': $src = imagecreatefromjpeg($sourceImageFile);
break;
case 'image/gif': $src = imagecreatefromgif($sourceImageFile);
break;
case 'image/png': $src = imagecreatefrompng($sourceImageFile);
break;
default:
$res = false;
}
}
# create corners
if ($res) {
$q = 10; # change this if you want
$radius *= $q;
# find unique color
do {
$r = rand(0, 255);
$g = rand(0, 255);
$b = rand(0, 255);
}
while (imagecolorexact($src, $r, $g, $b) < 0);
$nw = $w*$q;
$nh = $h*$q;
$img = imagecreatetruecolor($nw, $nh);
$alphacolor = imagecolorallocatealpha($img, $r, $g, $b, 127);
imagealphablending($img, false);
imagesavealpha($img, true);
imagefilledrectangle($img, 0, 0, $nw, $nh, $alphacolor);
imagefill($img, 0, 0, $alphacolor);
imagecopyresampled($img, $src, 0, 0, 0, 0, $nw, $nh, $w, $h);
imagearc($img, $radius-1, $radius-1, $radius*2, $radius*2, 180, 270, $alphacolor);
imagefilltoborder($img, 0, 0, $alphacolor, $alphacolor);
imagearc($img, $nw-$radius, $radius-1, $radius*2, $radius*2, 270, 0, $alphacolor);
imagefilltoborder($img, $nw-1, 0, $alphacolor, $alphacolor);
imagearc($img, $radius-1, $nh-$radius, $radius*2, $radius*2, 90, 180, $alphacolor);
imagefilltoborder($img, 0, $nh-1, $alphacolor, $alphacolor);
imagearc($img, $nw-$radius, $nh-$radius, $radius*2, $radius*2, 0, 90, $alphacolor);
imagefilltoborder($img, $nw-1, $nh-1, $alphacolor, $alphacolor);
imagealphablending($img, true);
imagecolortransparent($img, $alphacolor);
# resize image down
$dest = imagecreatetruecolor($w, $h);
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagefilledrectangle($dest, 0, 0, $w, $h, $alphacolor);
imagecopyresampled($dest, $img, 0, 0, 0, 0, $w, $h, $nw, $nh);
$res = $dest;
imagepng( $res,$outputfile );
}
}
}
?>
I load the component in MyController :
App::import('Component', 'Image');
$MyImageCom = new ImageComponent();
But, when I just load the component, I recieve this error:
Error: Class 'Object' not found File:
/Applications/XAMPP/xamppfiles/htdocs/aurum/app/Controller/Component/ImageComponent.php
Line: 2

You're extending a class which isn't exists.
Instead of:
class ImageComponent extends Object {
Use:
class ImageComponent extends Component {
Example From Cakephp manual:
App::uses('Component', 'Controller');
class MathComponent extends Component { //not Object
public function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
}

Related

Add metadata to image using GD

I have image uploaded on the server in jpg format, everytime browser request a image if image not exist in webp i resize and conver image into webp format.
Since here everything work fine but new converted image (webp) is missing metadata like author, copyright, comment .... from original image.
Is there any way to add medatata from original image to converted (webp) image during resizing or converting ?
this is my code
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save_webp(DIR_IMAGE . $new_image_webp, $quality);
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->info['width'] || !$this->info['height']) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->info['width'];
$scale_h = $height / $this->info['height'];
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png') {
return;
}
$new_width = (int)($this->info['width'] * $scale);
$new_height = (int)($this->info['height'] * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $width;
$this->info['height'] = $height;
}
public function save_webp($file, $quality = 40) {
if (is_resource($this->image)) {
imagewebp($this->image, $file, $quality);
imagedestroy($this->image);
}
}

imagecopyresampled after rotating the image

I am trying to copy image (to $img) after rotating image (many images $im) but I get weird behavior. Once I un-comment the line //$img = I only get the rotated image on my final output. Can I rotate the inner $im and copy it to final image$img?
<?php
$height = 80;
$width = 300;
$img = imagecreate($width, $height);
$c = imagecolorallocate ($img , 135, 135, 135);
imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));
for($i=0; $i<=5; $i++){
$im = imagecreatetruecolor(35, 35);
$gry = imagecolorallocate($im, 135, 135, 135);
$wht = imagecolorallocate($im, 255, 255, 255);
$j = mt_rand(0, 1);
$ch = mt_rand(0,1)?chr(rand(65, 90)):chr(rand(97, 122));
if($j == 0){
imagefill($im, 0, 0, $wht);
imagefttext($im, 20, 0, 3, 21, $gry, 'AHGBold.ttf', $ch);
//$img = imagerotate($im, mt_rand(0,10)-5, $wht);
}else{
imagefill($im, 0, 0, $gry);
imagefttext($im, 20, 0, 3, 21, $wht, 'AHGBold.ttf', $ch);
//$img = imagerotate($im, mt_rand(0,10)-5, $gry);
}
imagecopyresampled($img, $im, 5 + $i*42, $height/2 - 12, 0, 0, 40, 40, 25, 25);
}
header('Content-type: image/png');
imagepng($img);
change
$img = imagerotate($im, mt_rand(0,10)-5, $wht);
and
$img = imagerotate($im, mt_rand(0,10)-5, $gry);
to
$im = imagerotate($im, mt_rand(0,10)-5, $wht);
and
$im = imagerotate($im, mt_rand(0,10)-5, $gry);
in cases that imagerotes does not work you can use the following function to rotate an image:
function imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0)
{
$srcw = imagesx($srcImg);
$srch = imagesy($srcImg);
if($angle == 0) return $srcImg;
// Convert the angle to radians
$theta = deg2rad ($angle);
// Calculate the width of the destination image.
$temp = array ( rotateX(0, 0, 0-$theta),
rotateX($srcw, 0, 0-$theta),
rotateX(0, $srch, 0-$theta),
rotateX($srcw, $srch, 0-$theta)
);
$minX = floor(min($temp));
$maxX = ceil(max($temp));
$width = $maxX - $minX;
// Calculate the height of the destination image.
$temp = array ( rotateY(0, 0, 0-$theta),
rotateY($srcw, 0, 0-$theta),
rotateY(0, $srch, 0-$theta),
rotateY($srcw, $srch, 0-$theta)
);
$minY = floor(min($temp));
$maxY = ceil(max($temp));
$height = $maxY - $minY;
$destimg = imagecreatetruecolor($width, $height);
imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));
// sets all pixels in the new image
for($x=$minX;$x<$maxX;$x++) {
for($y=$minY;$y<$maxY;$y++)
{
// fetch corresponding pixel from the source image
$srcX = round(rotateX($x, $y, $theta));
$srcY = round(rotateY($x, $y, $theta));
if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
{
$color = imagecolorat($srcImg, $srcX, $srcY );
}
else
{
$color = $bgcolor;
}
imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
}
}
return $destimg;
}
function rotateX($x, $y, $theta){
return $x * cos($theta) - $y * sin($theta);
}
function rotateY($x, $y, $theta){
return $x * sin($theta) + $y * cos($theta);
}
I got the above code from a note in php.net

Creating PNG thumbnail using PHP

I'm trying to create a thumbnail image it returned an error, that imagecopyresized() expects 2 parameter to be resource, but it can create the image but the output is only a small black image.
here is my code
$image = "asd.PNG";
$image_size = getimagesize($image);
$image_width = $image_size[0];
$image_height = $image_size[1];
$new_size = ($image_width + $image_height)/($image_width*($image_height/45));
$new_width = $image_width * $new_size;
$new_height = $image_height * $new_size;
$new_image = imagecreatetruecolor($new_width, $new_height);
$old_mage = imagecreatefrompng($image);
imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
imagepng($new_image, $image.'.thumb.png');
Here's one function that does it. Uses assist function for PNG transparency.
public function redimesionImage($endThu,$newX,$newY,$endImg,$fileType){
// Copy the image to be resized
copy($endThu, $endImg);
// Retrieves the image data
list($width, $height) = getimagesize($endImg);
// If the width is greater ...
if($width >= $height) {
// I set the width of the image to the desired size ...
$newXimage = $newX;
// And calculate the size of the time to not stretch the image
$newYimage = ($height / $width) * $newXimage;
} else {
// Define the desired height ...
$newYimage = $newY;
// And calculate the width to not stretch the image
$newXimage = ($width / $height) * $newYimage;
}
// Creates an initial image in memory with calculated measures
$imageInicial = imagecreatetruecolor(ceil($newXimage), ceil($newYimage));
// I check the extension of the image and create their respective image
if ($fileType == 'jpeg') $endereco = imagecreatefromjpeg($endImg);
if ($fileType == 'jpg') $endereco = imagecreatefromjpeg($endImg);
if ($fileType == 'png') {
$endereco = imagecreatefrompng($endImg);
imagealphablending($imageInicial, false);
imagesavealpha($imageInicial,true);
$transparent = imagecolorallocatealpha($imageInicial, 255, 255, 255, 127);
imagefilledrectangle($endereco, 0, 0, $newXimage, $newYimage, $transparent);
}
if ($fileType == 'gif') {
$endereco = imagecreatefromgif($endImg);
$this->setTransparency($imageInicial,$endereco);
}
// I merge the image to be resized with created in memory
imagecopyresampled($imageInicial, $endereco, 0, 0, 0, 0, ceil($newXimage), ceil($newYimage), ceil($width), ceil($height));
// Creates the image in its final lacal, according to its extension
if ($fileType == 'jpeg') imagejpeg($imageInicial, $endImg, 100);
if ($fileType == 'jpg') imagejpeg($imageInicial, $endImg, 100);
if ($fileType == 'png') imagepng($imageInicial, $endImg, 9);
if ($fileType == 'gif') imagegif($imageInicial, $endImg, 100);
}
// Function to assist the PNG images, sets the transparency in the image
private function setTransparency($new_image,$image_source){
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if($transparencyIndex >= 0){
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
public function redimesionImage($endThu,$newX,$newY,$endImg,$fileType){
copy($endThu, $endImg);
list($width, $height) = getimagesize($endImg);
if($width >= $height) {
$newXimage = $newX;
$newYimage = ($height / $width) * $newXimage;
} else {
$newYimage = $newY;
$newXimage = ($width / $height) * $newYimage;
}
$imageInicial = imagecreatetruecolor(ceil($newXimage), ceil($newYimage));
if ($fileType == 'jpeg') $endereco = imagecreatefromjpeg($endImg);
if ($fileType == 'jpg') $endereco = imagecreatefromjpeg($endImg);
if ($fileType == 'png') {
$endereco = imagecreatefrompng($endImg);
imagealphablending($imageInicial, false);
imagesavealpha($imageInicial,true);
$transparent = imagecolorallocatealpha($imageInicial, 255, 255, 255, 127);
imagefilledrectangle($endereco, 0, 0, $newXimage, $newYimage, $transparent);
}
if ($fileType == 'gif') {
$endereco = imagecreatefromgif($endImg);
$this->setTransparency($imageInicial,$endereco);
}
imagecopyresampled($imageInicial, $endereco, 0, 0, 0, 0, ceil($newXimage), ceil($newYimage), ceil($width), ceil($height));
if ($fileType == 'jpeg') imagejpeg($imageInicial, $endImg, 100);
if ($fileType == 'jpg') imagejpeg($imageInicial, $endImg, 100);
if ($fileType == 'png') imagepng($imageInicial, $endImg, 9);
if ($fileType == 'gif') imagegif($imageInicial, $endImg, 100);
}
private function setTransparency($new_image,$image_source){
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if($transparencyIndex >= 0){
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
You use imagecreatefrompng() to load a picture, so you must make sure the picture format is png, not jpeg or other format. you can have a test use function imagecreatefromjpeg()
Here are the two different ways to create a thumbnail.
First way
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if($original_type == 1 || $original_type == 2) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($original_type == 3){
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
//imagesavealpha($new_image, TRUE);
//$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
//imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}
Another way:
function createThumbnails($filepath, $thumbpath, $thumbnail_height, $background=false) {
list($width, $height, $original_type) = getimagesize($filepath);
$new_width = floor( $width * ( $thumbnail_height / $height ) );
$new_height = $thumbnail_height;
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($new_width, $new_height); // creates new image, but with a black background
// figuring out the color for the background
if($original_type == 1 || $original_type == 2) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($original_type == 3){
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
//imagesavealpha($new_image, TRUE);
//$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
//imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}

PHP image resize function doesn't work properly

I want to resize an image PNG with transparence plz help. Here is the code :
function createThumb($upfile, $dstfile, $max_width, $max_height){
$size = getimagesize($upfile);
$width = $size[0];
$height = $size[1];
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if( ($width <= $max_width) && ($height <= $max_height)) {
$tn_width = $width;
$tn_height = $height;
} elseif (($x_ratio * $height) < $max_height) {
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
} else {
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
if($size['mime'] == "image/jpeg"){
$src = ImageCreateFromJpeg($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
imageinterlace( $dst, true);
ImageJpeg($dst, $dstfile, 100);
} else if ($size['mime'] == "image/png"){
$src = ImageCreateFrompng($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($dst, 255, 255, 0);
// removing the black from the placeholder
imagecolortransparent($dst, $background);
// turning off alpha blending (to ensure alpha channel information
// is preserved, rather than removed (blending with the rest of the
// image in the form of black))
imagealphablending($dst, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($dst, true);
Imagepng($dst, $dstfile);
} else {
$src = ImageCreateFromGif($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
imagegif($dst, $dstfile);
}
}
The image source :
The current result (that I don't want) is :
How can I resize the image and maintain the transparency of the background color? Need help, please. Thanks.
imagecopyresampled is in the wrong place. This should be called after you have set the background colour:
$src = ImageCreateFrompng($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
// use imagecolorallocatealpha to set BG as transparent:
$background = imagecolorallocatealpha($dst, 255, 255, 255, 127);
// turning off alpha blending as it's not needed
imagealphablending($dst, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($dst, true);
// Do this here!
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
Imagepng($dst, $dstfile);
<?php
function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
if(file_exists($newname))
#unlink($newname);
if(!file_exists($name))
return false;
$arr = split("\.",$name);
$ext = $arr[count($arr)-1];
if($ext=="jpeg" || $ext=="jpg"){
$img = #imagecreatefromjpeg($name);
} elseif($ext=="png"){
$img = #imagecreatefrompng($name);
} elseif($ext=="gif") {
$img = #imagecreatefromgif($name);
}
if(!$img)
return false;
$old_x = imageSX($img);
$old_y = imageSY($img);
if($old_x < $new_w && $old_y < $new_h) {
$thumb_w = $old_x;
$thumb_h = $old_y;
} elseif ($old_x > $old_y) {
$thumb_w = $new_w;
$thumb_h = floor(($old_y*($new_h/$old_x)));
} elseif ($old_x < $old_y) {
$thumb_w = floor($old_x*($new_w/$old_y));
$thumb_h = $new_h;
} elseif ($old_x == $old_y) {
$thumb_w = $new_w;
$thumb_h = $new_h;
}
$thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
$thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
$new_img = ImageCreateTrueColor($thumb_w, $thumb_h);
if($transparency) {
if($ext=="png") {
imagealphablending($new_img, false);
$colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
imagefill($new_img, 0, 0, $colorTransparent);
imagesavealpha($new_img, true);
} elseif($ext=="gif") {
$trnprt_indx = imagecolortransparent($img);
if ($trnprt_indx >= 0) {
//its transparent
$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
$trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($new_img, 0, 0, $trnprt_indx);
imagecolortransparent($new_img, $trnprt_indx);
}
}
} else {
Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
}
imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
if($border) {
$black = imagecolorallocate($new_img, 0, 0, 0);
imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
}
if($base64) {
ob_start();
imagepng($new_img);
$img = ob_get_contents();
ob_end_clean();
$return = base64_encode($img);
} else {
if($ext=="jpeg" || $ext=="jpg"){
imagejpeg($new_img, $newname);
$return = true;
} elseif($ext=="png"){
imagepng($new_img, $newname);
$return = true;
} elseif($ext=="gif") {
imagegif($new_img, $newname);
$return = true;
}
}
imagedestroy($new_img);
imagedestroy($img);
return $return;
}
//example useage
createthumb("1.png", "2.png", 64,64,true, true, false);
?>
Hope this can help...
I dont deserve credit for this code... just found it op net... enjoy

PHP/GD - Cropping and Resizing Images

I've coded a function that crops an image to a given aspect ratio and finally then resizes it and outputs it as JPG:
<?php
function Image($image, $crop = null, $size = null)
{
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image) === true)
{
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
/*
CROP (Aspect Ratio) Section
*/
if (is_null($crop) === true)
{
$crop = array($width, $height);
}
else
{
$crop = array_filter(explode(':', $crop));
if (empty($crop) === true)
{
$crop = array($width, $height);
}
else
{
if ((empty($crop[0]) === true) || (is_numeric($crop[0]) === false))
{
$crop[0] = $crop[1];
}
else if ((empty($crop[1]) === true) || (is_numeric($crop[1]) === false))
{
$crop[1] = $crop[0];
}
}
$ratio = array
(
0 => $width / $height,
1 => $crop[0] / $crop[1],
);
if ($ratio[0] > $ratio[1])
{
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
}
else if ($ratio[0] < $ratio[1])
{
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
/*
How can I skip (join) this operation
with the one in the Resize Section?
*/
$result = ImageCreateTrueColor($width, $height);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, false);
ImageFill($result, 0, 0, ImageColorAllocateAlpha($result, 255, 255, 255, 127));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $width, $height, $width, $height);
$image = $result;
}
}
/*
Resize Section
*/
if (is_null($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
$size = array_filter(explode('x', $size));
if (empty($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
if ((empty($size[0]) === true) || (is_numeric($size[0]) === false))
{
$size[0] = round($size[1] * imagesx($image) / imagesy($image));
}
else if ((empty($size[1]) === true) || (is_numeric($size[1]) === false))
{
$size[1] = round($size[0] * imagesy($image) / imagesx($image));
}
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, 0, 0, $size[0], $size[1], imagesx($image), imagesy($image));
header('Content-Type: image/jpeg');
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
?>
The function works as expected but I'm creating a non-required GD image resource, how can I fix it? I've tried joining both calls but I must be doing some miscalculations.
<?php
/*
Usage Examples
*/
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '1:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:', '250x300');
?>
Any help is greatly appreciated, thanks.
You will have to modify your resizing code not to be based on the cropped image to start with. Since you want to do the cropping and resizing in one go you need to calculate it independently.
<?php
function Image($image, $crop = ':', $size = null) {
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image)) {
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
// CROP (Aspect Ratio) Section
$crop = array_filter(explode(':', $crop));
if (empty($crop)) {
$crop = [$width, $height];
} else {
$crop[0] = $crop[0] ?: $crop[1];
$crop[1] = $crop[1] ?: $crop[0];
}
$ratio = [$width / $height, $crop[0] / $crop[1]];
if ($ratio[0] > $ratio[1]) {
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
} else {
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
// Resize Section
if (is_null($size)) {
$size = [$width, $height];
} else {
$size = array_filter(explode('x', $size));
if (empty($size)) {
$size = [imagesx($image), imagesy($image)];
} else {
$size[0] = $size[0] ?: round($size[1] * $width / $height);
$size[1] = $size[1] ?: round($size[0] * $height / $width);
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result)) {
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $size[0], $size[1], $width, $height);
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
header('Content-Type: image/jpeg');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '1:1', '600x');
?>

Categories