Create Multiple Images with php - php

I have that free php code-function (of Pedro Pinheiro https://github.com/pedroppinheiro)
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(is_array($background) && count($background) === 3) {
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($background === 'transparent' && $original_type === 3) {
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);
}`
it creates thumbnails from single image file when you call function like this
$success = createThumbnail(__DIR__.DIRECTORY_SEPARATOR.'image.jpg', __DIR__.DIRECTORY_SEPARATOR.'image_thumb.jpg', 60, 60, array(255,255,255));
It is okay for single image file but I want it to convert all images in a folder what should I do? When I use for each it does not work.
I am trying to develop a joomla module I have that code that grabbing images
static function getList($params) {
$filter = '\.png$|\.gif$|\.jpg$|\.bmp$';
$path = $params->get('path');
$files = JFolder::files(JPATH_BASE.$path,$filter);
$i=0;
$lists = array();
foreach ($files as $file) {
$lists[$i]['title'] = JFile::stripExt($file);
$lists[$i]['image'] = JURI::base().str_replace(DS,'/',substr($path,1)).'/'.$file;
$i++;
}
return $lists;
}
Then I add this to create thumbnails
<?php
$filepath=JUri::root() . '/images/';
$thumbpath=JUri::root() . '/images/thumbs/';
$success=createThumbnail($filepath, $thumbpath, 160, 160, array(0,0,0));
?>
<?php foreach ($lists as $item):?>
<div>
<?php echo $success;?>
</div>
<?php endforeach; ?>
But it fails. thanks in advance.

Related

Prestashop image resize - loss of quality

I'm using the newest version of Prestashop (1.6.1.5), and I've got some problems with quality of product images.
While resizing (creating thumbnails like large_default, home_default etc) grey stripes appears on destination image.
I followed prestashop code and noticed that it happens after imagecopyresized() function, I tried to replace it with imagecopyresampled() but it doesn't help much.
Here is a link to the original image http://postimg.org/image/ib42bh81t, and here is a link to resized one (the one with grey stripes) http://postimg.org/image/i3tpda7sx
Prestashop resize() method:
public static function resize($src_file, $dst_file, $dst_width = null, $dst_height = null, $file_type = 'jpg',
$force_type = false, &$error = 0, &$tgt_width = null, &$tgt_height = null, $quality = 5,
&$src_width = null, &$src_height = null)
{
if (PHP_VERSION_ID < 50300) {
clearstatcache();
} else {
clearstatcache(true, $src_file);
}
if (!file_exists($src_file) || !filesize($src_file)) {
return !($error = self::ERROR_FILE_NOT_EXIST);
}
list($tmp_width, $tmp_height, $type) = getimagesize($src_file);
$rotate = 0;
if (function_exists('exif_read_data') && function_exists('mb_strtolower')) {
$exif = #exif_read_data($src_file);
if ($exif && isset($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$src_width = $tmp_width;
$src_height = $tmp_height;
$rotate = 180;
break;
case 6:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = -90;
break;
case 8:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = 90;
break;
default:
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
// If PS_IMAGE_QUALITY is activated, the generated image will be a PNG with .jpg as a file extension.
// This allow for higher quality and for transparency. JPG source files will also benefit from a higher quality
// because JPG reencoding by GD, even with max quality setting, degrades the image.
if (Configuration::get('PS_IMAGE_QUALITY') == 'png_all'
|| (Configuration::get('PS_IMAGE_QUALITY') == 'png' && $type == IMAGETYPE_PNG) && !$force_type) {
$file_type = 'png';
}
if (!$src_width) {
return !($error = self::ERROR_FILE_WIDTH);
}
if (!$dst_width) {
$dst_width = $src_width;
}
if (!$dst_height) {
$dst_height = $src_height;
}
$width_diff = $dst_width / $src_width;
$height_diff = $dst_height / $src_height;
$ps_image_generation_method = Configuration::get('PS_IMAGE_GENERATION_METHOD');
if ($width_diff > 1 && $height_diff > 1) {
$next_width = $src_width;
$next_height = $src_height;
} else {
if ($ps_image_generation_method == 2 || (!$ps_image_generation_method && $width_diff > $height_diff)) {
$next_height = $dst_height;
$next_width = round(($src_width * $next_height) / $src_height);
$dst_width = (int)(!$ps_image_generation_method ? $dst_width : $next_width);
} else {
$next_width = $dst_width;
$next_height = round($src_height * $dst_width / $src_width);
$dst_height = (int)(!$ps_image_generation_method ? $dst_height : $next_height);
}
}
if (!ImageManager::checkImageMemoryLimit($src_file)) {
return !($error = self::ERROR_MEMORY_LIMIT);
}
$tgt_width = $dst_width;
$tgt_height = $dst_height;
$dest_image = imagecreatetruecolor($dst_width, $dst_height);
// If image is a PNG and the output is PNG, fill with transparency. Else fill with white background.
if ($file_type == 'png' && $type == IMAGETYPE_PNG) {
imagealphablending($dest_image, false);
imagesavealpha($dest_image, true);
$transparent = imagecolorallocatealpha($dest_image, 255, 255, 255, 127);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $transparent);
} else {
$white = imagecolorallocate($dest_image, 255, 255, 255);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $white);
}
$src_image = ImageManager::create($type, $src_file);
if ($rotate) {
$src_image = imagerotate($src_image, $rotate, 0);
}
if ($dst_width >= $src_width && $dst_height >= $src_height) {
imagecopyresized($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height);
} else {
ImageManager::imagecopyresampled($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height, $quality);
}
$write_file = ImageManager::write($file_type, $dest_image, $dst_file);
#imagedestroy($src_image);
return $write_file;
}
I also tried to change quality parameter to 100 or even changed image format to PNG in prestashop - no changes.
What else can I change to fix this quality issues? Any ideas?

how to resize the uploading image and moving to a folder

i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);

How to change PHP thumbnail image size?

I found a PHP script online which helps me to create a thumbnail of an uploaded image, there is only one problem: I don't know how to change the outcome size of the thumbnail. I found the tutorial at: http://www.w3schools.in/php/image-upload-and-generate-thumbnail-using-ajax-in-php/
Can anyone help me to change the outcome size of the thumbnail?
Here is my code so far:
<?php
function createDir($path){
if (!file_exists($path)) {
$old_mask = umask(0);
mkdir($path, 0777, TRUE);
umask($old_mask);
}
}
function createThumb($path1, $path2, $file_type, $new_w, $new_h, $squareSize = ''){
/* read the source image */
$source_image = FALSE;
if (preg_match("/jpg|JPG|jpeg|JPEG/", $file_type)) {
$source_image = imagecreatefromjpeg($path1);
}
elseif (preg_match("/png|PNG/", $file_type)) {
if (!$source_image = #imagecreatefrompng($path1)) {
$source_image = imagecreatefromjpeg($path1);
}
}
elseif (preg_match("/gif|GIF/", $file_type)) {
$source_image = imagecreatefromgif($path1);
}
if ($source_image == FALSE) {
$source_image = imagecreatefromjpeg($path1);
}
$orig_w = imageSX($source_image);
$orig_h = imageSY($source_image);
if ($orig_w < $new_w && $orig_h < $new_h) {
$desired_width = $orig_w;
$desired_height = $orig_h;
} else {
$scale = min($new_w / $orig_w, $new_h / $orig_h);
$desired_width = ceil($scale * $orig_w);
$desired_height = ceil($scale * $orig_h);
}
if ($squareSize != '') {
$desired_width = $desired_height = $squareSize;
}
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
// for PNG background white----------->
$kek = imagecolorallocate($virtual_image, 255, 255, 255);
imagefill($virtual_image, 0, 0, $kek);
if ($squareSize == '') {
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $orig_w, $orig_h);
} else {
$wm = $orig_w / $squareSize;
$hm = $orig_h / $squareSize;
$h_height = $squareSize / 2;
$w_height = $squareSize / 2;
if ($orig_w > $orig_h) {
$adjusted_width = $orig_w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($virtual_image, $source_image, -$int_width, 0, 0, 0, $adjusted_width, $squareSize, $orig_w, $orig_h);
}
elseif (($orig_w <= $orig_h)) {
$adjusted_height = $orig_h / $wm;
$half_height = $adjusted_height / 2;
imagecopyresampled($virtual_image, $source_image, 0,0, 0, 0, $squareSize, $adjusted_height, $orig_w, $orig_h);
} else {
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $squareSize, $squareSize, $orig_w, $orig_h);
}
}
if (#imagejpeg($virtual_image, $path2, 90)) {
imagedestroy($virtual_image);
imagedestroy($source_image);
return TRUE;
} else {
return FALSE;
}
}
?>
the function gets called by the following lines of code:
<?php
include('./functions.php');
/*defined settings - start*/
ini_set("memory_limit", "99M");
ini_set('post_max_size', '20M');
ini_set('max_execution_time', 600);
define('IMAGE_SMALL_DIR', './uploades/small/');
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_DIR', './uploades/medium/');
define('IMAGE_MEDIUM_SIZE', 250);
/*defined settings - end*/
if(isset($_FILES['image_upload_file'])){
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_upload_file']["error"] > 0) {
$output['error']= "Error in File";
}
elseif (!in_array($_FILES['image_upload_file']["type"], $allowedImageType)) {
$output['error']= "You can only upload JPG, PNG and GIF file";
}
elseif (round($_FILES['image_upload_file']["size"] / 1024) > 4096) {
$output['error']= "You can upload file size up to 4 MB";
} else {
/*create directory with 777 permission if not exist - start*/
createDir(IMAGE_SMALL_DIR);
createDir(IMAGE_MEDIUM_DIR);
/*create directory with 777 permission if not exist - end*/
$path[0] = $_FILES['image_upload_file']['tmp_name'];
$file = pathinfo($_FILES['image_upload_file']['name']);
$fileType = $file["extension"];
$desiredExt='jpg';
$fileNameNew = rand(333, 999) . time() . ".$desiredExt";
$path[1] = IMAGE_MEDIUM_DIR . $fileNameNew;
$path[2] = IMAGE_SMALL_DIR . $fileNameNew;
if (createThumb($path[0], $path[1], $fileType, IMAGE_MEDIUM_SIZE, IMAGE_MEDIUM_SIZE,IMAGE_MEDIUM_SIZE)) {
if (createThumb($path[1], $path[2],"$desiredExt", IMAGE_SMALL_SIZE, IMAGE_SMALL_SIZE,IMAGE_SMALL_SIZE)) {
$output['status']=TRUE;
$output['image_medium']= $path[1];
$output['image_small']= $path[2];
}
}
}
echo json_encode($output);
}
?>
I saw that you found the answer to your own problem. I wanted to add some additional insight.
The Right Way
Ideally you should be passing a param to the method as you can reset it if desired:
$imageSize = 100; // size
createThumb($path[0], $path[1], $fileType, $imageSize, $imageSize, $imageSize);
The Wrong Way
The script above is using constants. They are outlined with the define method. IE.
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_SIZE', 250);
Change the number to your desired size. Ie
define('IMAGE_SMALL_SIZE', 150);
In this particular use case, the constants are still being passed into the function which defeats the need for a constant.

Modify PHP code to change background color

I have this PHP code
if (!isset($_POST["imageSource"])) {
$_POST["imageSource"] = "test.jpg";
}
list($width, $height) = getimagesize($_POST["imageSource"]);
$viewPortW = $_POST["viewPortW"];
$viewPortH = $_POST["viewPortH"];
$pWidth = $_POST["imageW"];
$pHeight = $_POST["imageH"];
$ext = end(explode(".",$_POST["imageSource"]));
$function = returnCorrectFunction($ext);
$image = $function($_POST["imageSource"]);
$width = imagesx($image);
$height = imagesy($image);
// Resample
$image_p = imagecreatetruecolor($pWidth, $pHeight);
setTransparency($image,$image_p,$ext);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);
imagedestroy($image);
$widthR = imagesx($image_p);
$hegihtR = imagesy($image_p);
$selectorX = $_POST["selectorX"];
$selectorY = $_POST["selectorY"];
if($_POST["imageRotate"]){
$angle = 360 - $_POST["imageRotate"];
$image_p = imagerotate($image_p,$angle,0);
$pWidth = imagesx($image_p);
$pHeight = imagesy($image_p);
//print $pWidth."---".$pHeight;
$diffW = abs($pWidth - $widthR) / 2;
$diffH = abs($pHeight - $hegihtR) / 2;
$_POST["imageX"] = ($pWidth > $widthR ? $_POST["imageX"] - $diffW : $_POST["imageX"] + $diffW);
$_POST["imageY"] = ($pHeight > $hegihtR ? $_POST["imageY"] - $diffH : $_POST["imageY"] + $diffH);
}
$dst_x = $src_x = $dst_y = $src_y = 0;
if($_POST["imageX"] > 0){
$dst_x = abs($_POST["imageX"]);
}else{
$src_x = abs($_POST["imageX"]);
}
if($_POST["imageY"] > 0){
$dst_y = abs($_POST["imageY"]);
}else{
$src_y = abs($_POST["imageY"]);
}
$viewport = imagecreatetruecolor($_POST["viewPortW"],$_POST["viewPortH"]);
setTransparency($image_p,$viewport,$ext);
imagecopy($viewport, $image_p, $dst_x, $dst_y, $src_x, $src_y, $pWidth, $pHeight);
imagedestroy($image_p);
$selector = imagecreatetruecolor($_POST["selectorW"], $_POST["selectorH"]);
setTransparency($viewport,$selector,$ext);
imagecopy($selector, $viewport, 0, 0, $selectorX, $selectorY, $_POST["viewPortW"], $_POST["viewPortH"]);
if (isset($_GET["destino"]) && !empty($_GET["destino"])) {
$file = "../../".$_GET["destino"];
} else {
$file = "test".time().".".$ext;
}
parseImage($ext,$selector,$file);
imagedestroy($viewport);
//Return value
echo $file;
/* Functions */
function determineImageScale($sourceWidth, $sourceHeight, $targetWidth, $targetHeight) {
$scalex = $targetWidth / $sourceWidth;
$scaley = $targetHeight / $sourceHeight;
return min($scalex, $scaley);
}
function returnCorrectFunction($ext){
$function = "";
switch($ext){
case "png":
$function = "imagecreatefrompng";
break;
case "jpeg":
$function = "imagecreatefromjpeg";
break;
case "jpg":
$function = "imagecreatefromjpeg";
break;
case "gif":
$function = "imagecreatefromgif";
break;
}
return $function;
}
function parseImage($ext,$img,$file = null){
switch($ext){
case "png":
imagepng($img,($file != null ? $file : ''));
break;
case "jpeg":
imagejpeg($img,($file ? $file : ''),100);
break;
case "jpg":
imagejpeg($img,($file ? $file : ''),100);
break;
case "gif":
imagegif($img,($file ? $file : ''));
break;
}
}
function setTransparency($imgSrc,$imgDest,$ext){
if($ext == "png" || $ext == "gif"){
$trnprt_indx = imagecolortransparent($imgSrc);
// If we have a specific transparent color
if ($trnprt_indx >= 0) {
// Get the original image's transparent color's RGB values
$trnprt_color = imagecolorsforindex($imgSrc, $trnprt_indx);
// Allocate the same color in the new image resource
$trnprt_indx = imagecolorallocate($imgDest, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
// Completely fill the background of the new image with allocated color.
imagefill($imgDest, 0, 0, $trnprt_indx);
// Set the background color for new image to transparent
imagecolortransparent($imgDest, $trnprt_indx);
}
// Always make a transparent background color for PNGs that don't have one allocated already
elseif ($ext == "png") {
// Turn off transparency blending (temporarily)
imagealphablending($imgDest, true);
// Create a new transparent color for image
$color = imagecolorallocatealpha($imgDest, 0, 0, 0, 127);
// Completely fill the background of the new image with allocated color.
imagefill($imgDest, 0, 0, $color);
// Restore transparency blending
imagesavealpha($imgDest, true);
}
}
}
Comes Cropzoom tool
Currently I generated JPG images with black background color.
I need to modify it so you can change (from the code) background color of the generated image in JPG format
All other things are working properly.
I have solved the problem.
I used this to give background color on all parts that I considered necessary
$backgroundColor = "FF0000"; // Red, for example
$backgroundColor= '0x'.$backgroundColor;
imagefilledrectangle($FinalImage, 0 , 0 , $width , $height , ($backgroundColor*1));
The full code
// Set the Background color
$background_color = "FFFFFF";
$background_color = "0x".$background_color;
if (!isset($_POST["imageSource"])) {
$_POST["imageSource"] = "test.jpg";
}
list($width, $height) = getimagesize($_POST["imageSource"]);
$viewPortW = $_POST["viewPortW"];
$viewPortH = $_POST["viewPortH"];
$pWidth = $_POST["imageW"];
$pHeight = $_POST["imageH"];
$ext = end(explode(".",$_POST["imageSource"]));
$function = returnCorrectFunction($ext);
$image = $function($_POST["imageSource"]);
$width = imagesx($image);
$height = imagesy($image);
// Modified to set background color
$image_p = imagecreatetruecolor($pWidth, $pHeight);
// ****************************************************************
// ********** NEXT LINE IS NEW TO SET BACKGROUND COLOR **************
// ****************************************************************
imagefilledrectangle($viewport, 0, 0, $pWidth, $pHeight, ($background_color * 1));
setTransparency($image,$image_p,$ext);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);
imagedestroy($image);
$widthR = imagesx($image_p);
$hegihtR = imagesy($image_p);
$selectorX = $_POST["selectorX"];
$selectorY = $_POST["selectorY"];
if($_POST["imageRotate"]){
$angle = 360 - $_POST["imageRotate"];
$image_p = imagerotate($image_p,$angle,0);
$pWidth = imagesx($image_p);
$pHeight = imagesy($image_p);
//print $pWidth."---".$pHeight;
$diffW = abs($pWidth - $widthR) / 2;
$diffH = abs($pHeight - $hegihtR) / 2;
$_POST["imageX"] = ($pWidth > $widthR ? $_POST["imageX"] - $diffW : $_POST["imageX"] + $diffW);
$_POST["imageY"] = ($pHeight > $hegihtR ? $_POST["imageY"] - $diffH : $_POST["imageY"] + $diffH);
}
$dst_x = $src_x = $dst_y = $src_y = 0;
if($_POST["imageX"] > 0){
$dst_x = abs($_POST["imageX"]);
}else{
$src_x = abs($_POST["imageX"]);
}
if($_POST["imageY"] > 0){
$dst_y = abs($_POST["imageY"]);
}else{
$src_y = abs($_POST["imageY"]);
}
$viewport = imagecreatetruecolor($_POST["viewPortW"],$_POST["viewPortH"]);
// ****************************************************************
// ********** NEXT LINE IS NEW TO SET BACKGROUND COLOR **************
// ****************************************************************
imagefilledrectangle($viewport, 0, 0, $_POST["viewPortW"], $_POST["viewPortH"], ($background_color * 1));
setTransparency($image_p,$viewport,$ext);
imagecopy($viewport, $image_p, $dst_x, $dst_y, $src_x, $src_y, $pWidth, $pHeight);
imagedestroy($image_p);
$selector = imagecreatetruecolor($_POST["selectorW"], $_POST["selectorH"]);
setTransparency($viewport,$selector,$ext);
imagecopy($selector, $viewport, 0, 0, $selectorX, $selectorY, $_POST["viewPortW"], $_POST["viewPortH"]);
if (isset($_GET["destino"]) && !empty($_GET["destino"])) {
$file = "../../".$_GET["destino"];
} else {
$file = "test".time().".".$ext;
}
parseImage($ext,$selector,$file);
imagedestroy($viewport);
//Return value
echo $file;
/* Functions */
function determineImageScale($sourceWidth, $sourceHeight, $targetWidth, $targetHeight) {
$scalex = $targetWidth / $sourceWidth;
$scaley = $targetHeight / $sourceHeight;
return min($scalex, $scaley);
}
function returnCorrectFunction($ext){
$function = "";
switch($ext){
case "png":
$function = "imagecreatefrompng";
break;
case "jpeg":
$function = "imagecreatefromjpeg";
break;
case "jpg":
$function = "imagecreatefromjpeg";
break;
case "gif":
$function = "imagecreatefromgif";
break;
}
return $function;
}
function parseImage($ext,$img,$file = null){
switch($ext){
case "png":
imagepng($img,($file != null ? $file : ''));
break;
case "jpeg":
imagejpeg($img,($file ? $file : ''),100);
break;
case "jpg":
imagejpeg($img,($file ? $file : ''),100);
break;
case "gif":
imagegif($img,($file ? $file : ''));
break;
}
}
function setTransparency($imgSrc,$imgDest,$ext){
if($ext == "png" || $ext == "gif"){
$trnprt_indx = imagecolortransparent($imgSrc);
// If we have a specific transparent color
if ($trnprt_indx >= 0) {
// Get the original image's transparent color's RGB values
$trnprt_color = imagecolorsforindex($imgSrc, $trnprt_indx);
// Allocate the same color in the new image resource
$trnprt_indx = imagecolorallocate($imgDest, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
// Completely fill the background of the new image with allocated color.
imagefill($imgDest, 0, 0, $trnprt_indx);
// Set the background color for new image to transparent
imagecolortransparent($imgDest, $trnprt_indx);
}
// Always make a transparent background color for PNGs that don't have one allocated already
elseif ($ext == "png") {
// Turn off transparency blending (temporarily)
imagealphablending($imgDest, true);
// Create a new transparent color for image
$color = imagecolorallocatealpha($imgDest, 0, 0, 0, 127);
// Completely fill the background of the new image with allocated color.
imagefill($imgDest, 0, 0, $color);
// Restore transparency blending
imagesavealpha($imgDest, true);
}
}
}
It is modified after "NEXT LINE IS NEW TO SET BACKGROUND COLOR" and all the tests I've done, it works correctly

CAn't resize image with GDlib2

I'm trying to resize an image of more than 3000px in width, it uploads fine if i do not resize it, but as soon as I resize the image it does not want to upload and resize, this is funny and I can't seem to understnd, since if the width of the image is alot smaller everthing works just fine. Are there limitations to this?
Try this... Not Using GD but i think it will work for u.
<?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;
}
}
/*
Resize Section
*/
if (is_null($size) === true) {
$size = array($width, $height);
}
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] * $width / $height);
} else if ((empty($size[1]) === true) || (is_numeric($size[1]) === false)) {
$size[1] = round($size[0] * $height / $width);
}
}
}
$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, $x, $y, $size[0], $size[1], $width, $height);
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
header('Content-Type: image/jpeg');
Image('image.jpg', '2:1', '1200x');
?>

Categories