Modify PHP code to change background color - php

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

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?

Create thumbnails, fixed sizes - PHP

I want to create thumbnails from image, but fixed sizes - 310px width, 217px height.
My code:
list($width, $height) = getimagesize($filename);
$width = 310;
$height = 217;
$new_width = 310;
$new_height = 217;
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);......
How can I make that? What is the formula?
function resizeImage($url, $width, $height, $url_out, $keep_ratio = false){
if($height <= 0 && $width <= 0)
return false;
else{
copy($url, $url_out);
$info = getimagesize($url);
$image = '';
$final_width = 0;
$final_height = 0;
list($width_old, $height_old) = $info;
if($keep_ratio){
if($width == 0)
$factor = $height/$height_old;
elseif($height == 0)
$factor = $width/$width_old;
else
$factor = min($width / $width_old, $height / $height_old);
$final_width = round( $width_old * $factor );
$final_height = round( $height_old * $factor );
}
else{
$final_width = ($width <= 0) ? $width_old : $width;
$final_height = ($height <= 0) ? $height_old : $height;
}
switch($info[2]){
case IMAGETYPE_GIF:
$image = imagecreatefromgif($url_out);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($url_out);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($url_out);
break;
default:
return false;
}
$image_resized = imagecreatetruecolor($final_width, $final_height);
if($info[2] == IMAGETYPE_GIF || $info[2] == IMAGETYPE_PNG){
$transparency = imagecolortransparent($image);
if($transparency >= 0){
$transparent_color = imagecolorsforindex($image, $trnprt_indx);
$transparency = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($image_resized, 0, 0, $transparency);
imagecolortransparent($image_resized, $transparency);
}
elseif($info[2] == IMAGETYPE_PNG){
imagealphablending($image_resized, false);
$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
imagefill($image_resized, 0, 0, $color);
imagesavealpha($image_resized, true);
}
}
imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);
switch($info[2]){
case IMAGETYPE_GIF:
imagegif($image_resized, $url_out);
break;
case IMAGETYPE_JPEG:
imagejpeg($image_resized, $url_out);
break;
case IMAGETYPE_PNG:
imagepng($image_resized, $url_out);
break;
default:
return false;
}
imagedestroy($image_resized);
return true;
}
}
//just call the function, and change the image name
$url="desert09.jpg";
resizeImage($url, 310, 217,"output.jpg", $keep_ratio = false);
I have this code (i don't remember where i got it) and i have edited it a little. I hope it can help you, this create a fixed square size thumb:
/** Create a square cropped thumb **/
function createSquareCroppedThumb($path , $thumbPath, $thumbSize = 100 ){
global $max_width, $max_height;
/* Set Filenames */
$srcFile = $path;
$thumbFile = $thumbPath;
/* Determine the File Type */
$type = pathinfo($path, PATHINFO_EXTENSION);
/* Create the Source Image */
switch( $type ){
case 'jpg' : case 'jpeg' :
$src = imagecreatefromjpeg( $srcFile ); break;
case 'png' :
$src = imagecreatefrompng( $srcFile ); break;
case 'gif' :
$src = imagecreatefromgif( $srcFile ); break;
}
/* Determine the Image Dimensions */
$oldW = imagesx( $src );
$oldH = imagesy( $src );
$minValue = $oldH > $oldW ? $oldW : $oldH;
/* Create the New Image */
$new = imagecreatetruecolor( $thumbSize , $thumbSize );
/* Transcribe the Source Image into the New (Square) Image */
imagecopyresampled($new , $src , 0 , 0 , ($oldW / 2) - ($minValue /2) , ($oldH / 2) - ($minValue /2) , $thumbSize , $thumbSize , $minValue , $minValue );
switch( $type ){
case 'jpg' : case 'jpeg' :
$src = imagejpeg( $new , $thumbFile ); break;
case 'png' :
$src = imagepng( $new , $thumbFile ); break;
case 'gif' :
$src = imagegif( $new , $thumbFile ); break;
}
imagedestroy( $new );
}

Resize an image and save with imagejpeg()

iam trying to resize an imageto a thumbnail with php! I get no errors but it won't save the thumbnail on my server. The code is:
#Resize image
function resize($input_dir, $cur_file, $newwidth, $output_dir)
{
$filename = $input_dir.'/'.$cur_file;
$format='';
if(preg_match("/.jpg/i", $filename))
{
$format = 'image/jpeg';
}
if (preg_match("/.gif/i", $filename))
{
$format = 'image/gif';
}
if(preg_match("/.png/i", $filename))
{
$format = 'image/png';
}
if($format!='')
{
list($width, $height) = getimagesize($filename);
$newheight=$height*$newwidth/$width;
switch($format)
{
case 'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case 'image/gif';
$source = imagecreatefromgif($filename);
break;
case 'image/png':
$source = imagecreatefrompng($filename);
break;
}
$thumb = imagecreatetruecolor($newwidth,$newheight);
imagealphablending($thumb, false);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, 'thumb_'.$cur_file);
}
}
My function looks like:
resize(plugins_url().'/MyImagePlugin/img', 'testimg.jpg', "200");
The Image is in the Folder "img" in my Plugin Dic. The wired thing is ,that i don't get any erros?! CHMOD is 777 for img-folder.
Any help would be appreciated.
You are not using any path when you save the image in the line:
imagejpeg($thumb, 'thumb_'.$cur_file);
$cur_file is set to testing.jpg.
You should add the path to the filename or it will be attempoting to create it in whatever the current directory is.
Changes are something like :
function resize($input_dir, $cur_file, $newwidth, $output_dir = "" )
{
if($output_dir == "") $output_dir = $input_dir;
.....
imagejpeg($thumb, $output_dir.'/thumb_'.$cur_file);
}
}
I know that this is not your way of doing but iam sure it can help you.
if (isset($_FILES['image']['name']))
{
$saveto = "dirname/file.jpg";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 500;
\\ you can change this to desired product for height and width.
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}

image thumbnailer creating a black background

This is a pretty typical script to create a thumbnail. How come it keeps outputting a black canvas instead of the white I am trying to specify? Am I missing something totally obvious here?
<?php
$image = 'images/original/' . $_GET['image'];
$thumb = "images/thumbs/t_" . $_GET['image'];
$size = 220;
square_crop($image, $thumb, $size);
function square_crop($src_image, $dest_image, $thumb_size, $jpg_quality = 100)
{
// Get dimensions of existing image
$image = getimagesize($src_image);
// Check for valid dimensions
if( $image[0] <= 0 || $image[1] <= 0 ) return false;
// Determine format from MIME-Type
$image['format'] = strtolower(preg_replace('/^.*?\//', '', $image['mime']));
// Import image
switch( $image['format'] ) {
case 'jpg':
case 'jpeg':
$image_data = imagecreatefromjpeg($src_image);
break;
case 'png':
$image_data = imagecreatefrompng($src_image);
break;
case 'gif':
$image_data = imagecreatefromgif($src_image);
break;
default:
// Unsupported format
return false;
break;
}
// Verify import
if( $image_data == false ) return false;
// Calculate measurements
if( $image[0] & $image[1] ) {
// For landscape images
$x_offset = ($image[0] - $image[1]) / 2;
$y_offset = 0;
$square_size = $image[0] - ($x_offset * 2);
} else {
// For portrait and square images
$x_offset = 0;
$y_offset = ($image[1] - $image[0]) / 2;
$square_size = $image[1] - ($y_offset * 2);
}
//$im = imagecreatetruecolor(100, 100);
// sets background to red
//$red = imagecolorallocate($im, 255, 0, 0);
//imagefill($im, 0, 0, $red);
// Resize and crop
$canvas = imagecreatetruecolor($thumb_size, $thumb_size);
//make the background white
$white = imagecolorallocate($canvas, 255, 255, 255);
imagefill($canvas, 0,0, $white);
if( imagecopyresampled(
$canvas,
$image_data,
0,
0,
$x_offset,
$y_offset,
$thumb_size,
$thumb_size,
$square_size,
$square_size))
{
// Create thumbnail
switch( strtolower(preg_replace('/^.*\./', '', $dest_image)) ) {
case 'jpg':
case 'jpeg':
return imagejpeg($canvas, $dest_image, $jpg_quality);
break;
case 'png':
return imagepng($canvas, $dest_image);
break;
case 'gif':
return imagegif($canvas, $dest_image);
break;
default:
// Unsupported format
return false;
break;
}
} else {
return false;
}
}
?>

Black square at bottom on output thumbnail

I'm having a black area at my output imagecopyresized() thumbnail image.
My code:
function thumbImage($src){
/* thumb */
list($height, $width) = getimagesize($src);
$rel_difference_thumb = array('width'=>0, 'height'=>0);
if($width > 79) { $rel_difference_thumb['width'] = ($width-79)/79; }
if($height > 105) { $rel_difference_thumb['height'] = ($height-105)/105; }
asort($rel_difference_thumb);
$newwidth_thumb = $width/(1+end($rel_difference_thumb));
$newheight_thumb = $height/(1+end($rel_difference_thumb));
$newwidth_thumb = round($newwidth_thumb);
$newheight_thumb = round($newheight_thumb);
$jpeg_quality_thumb = 90;
$thumbloc = 'images/users/privAlbum/thumb/'.$USER . md5(uniqid()) . '.jpg';
switch(exif_imagetype($src)) {
case IMAGETYPE_GIF:
$img_r_thumb = imagecreatefromgif($src);
break;
case IMAGETYPE_JPEG:
$img_r_thumb = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$img_r_thumb = imagecreatefrompng($src);
break;
default:
echo json_encode(array('error' => 'Ingen bild!'));
exit(0);
break;
}
$dst_r_thumb = ImageCreateTrueColor( $newwidth_thumb, $newheight_thumb );
imagecopyresized($dst_r_thumb, $img_r_thumb, 0, 0, 0, 0, $newwidth_thumb , $newheight_thumb, $width, $height);
if( imagejpeg($dst_r_thumb,$thumbloc,$jpeg_quality_thumb) ) {
return true;
}
imagedestroy($img_r_thumb);
}
Why is this happening? How can I fix this?
list($height, $width) = getimagesize($src); should be list($width, $height) = getimagesize($src);
as said on the manual on getimagesize :
Returns an array with 7 elements:
Index 0 and 1 contains respectively
the width and the height of the image.

Categories