Related
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);
}
}
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);
}
This question already has answers here:
Resize image in PHP
(13 answers)
Closed 6 years ago.
function resize($originalImage){
list($width, $height) = getimagesize($originalImage);
$newName=basename($originalImage);
$imageResized = imagecreatetruecolor(128, 128);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 128, 128, $width, $height);
imagejpeg($imageResized, "resizedImg/$newName",100);
imageDestroy($imageResized);
}
The script returns the image with the correct name but it's just black? Any ideas?
If you have trouble with image resizing use this code for it. Do the modifications as you need it.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}
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
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');
?>