ImageCreateTrueColor creates black image - php

I'm trying to crop my image, but when I do it shows up as the right size, but all black. I've tried at least a dozen different scripts but I can't seem to get any of them to work :(
Oh and the rotation script works fine, and all of the echos are just for testing and will be removed :D
<?php
$staffID = $_POST['u'];
$actCode = $_POST['a'];
$tempAvatar = $_POST['tempAvatar'];
$x1 = $_POST['x'];
$y1 = $_POST['y'];
$wH = $_POST['w'];
$scale = $_POST['scale'];
$angle = $_POST['angle'];
$destFolder = "../../../avatars/";
$imagePath = "tempAvatars/".$tempAvatar.".jpg";
$imagePathRot = "tempAvatars/".$tempAvatar."ROTATED.jpg";
$imagePathCropped= "tempAvatars/".$tempAvatar."CROPPED.jpg";
echo 'X1: '.$x1.'<br>Y1: '.$y1.'<br>Width/Height: '.$wH.'<br>Angle: '.$angle;
if ($angle != 0) {
$source = imagecreatefromjpeg($imagePath) or notfound();
$rotate = imagerotate($source,$angle,0);
imagejpeg($rotate, $imagePathRot);
$imagePath = $imagePathRot;
}
echo '<br>X2: '.$x2.'<br>Y2: '.$y2;
$targ_w = 300;
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($imagePath);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_w );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['w']);
imagejpeg($dst_r, $imagePathCropped, $jpeg_quality);
echo '<br><img src="'.$imagePathCropped.'">';
?>

Related

Rotate and then crop image with PHP

I'm trying to crop my image, but when I do it shows up as the right size, but all black. I've tried at least a dozen different scripts but I can't seem to get any of them to work :(
Oh and the rotation script works fine, and all of the echos are just for testing and will be removed :D
<?php
$staffID = $_POST['u'];
$actCode = $_POST['a'];
$tempAvatar = $_POST['tempAvatar'];
$x1 = $_POST['x'];
$y1 = $_POST['y'];
$wH = $_POST['w'];
$scale = $_POST['scale'];
$angle = $_POST['angle'];
$destFolder = "../../../avatars/";
$imagePath = "tempAvatars/".$tempAvatar.".jpg";
$imagePathRot = "tempAvatars/".$tempAvatar."ROTATED.jpg";
$imagePathCropped= "tempAvatars/".$tempAvatar."CROPPED.jpg";
echo 'X1: '.$x1.'<br>Y1: '.$y1.'<br>Width/Height: '.$wH.'<br>Angle: '.$angle;
if ($angle != 0) {
$source = imagecreatefromjpeg($imagePath) or notfound();
$rotate = imagerotate($source,$angle,0);
imagejpeg($rotate, $imagePathRot);
$imagePath = $imagePathRot;
}
echo '<br>X2: '.$x2.'<br>Y2: '.$y2;
$targ_w = 300;
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($imagePath);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_w );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['w']);
imagejpeg($dst_r, $imagePathCropped, $jpeg_quality);
echo '<br><img src="'.$imagePathCropped.'">';
?>
Your problem is that $targ_h is not defined, therefore you are copying 0 pixel "rows" from the source image. It's in the correct size because it's decided by ImageCreateTrueColor and of course initialized to black. The correct call according to the rest of your code should be:
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_w,$_POST['w'],$_POST['w']);

How do I allow PNG's in my crop script?

I've got an upload function that allows both Jpegs and PNG's. After the image is uploaded, a php file is called that handles a crop function to crop the uploaded image.
After the image is cropped, it is once again saved to the server under a new name. In this current setup, only jpegs are able to be written to the server. Anything else will draw a black image.
I was wondering How I write this code so that the crop also allows PNG's
The code that handles the crop:
$imageLocation = $_SESSION['image_location'];
$newNameOverwrite = $_SESSION['new_name'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
imagejpeg($dst_r,$name,100);
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
//Thumbnail generate
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Updated code:
$imageType = $_SESSION['image_type'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;
$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
if ($imageType == '.jpg' || $imageType == '.jpeg'){
$img_r = imagecreatefromjpeg($src);
}
if ($imageType == '.png'){
$img_r = imagecreatefrompng($src);
}
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;
imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
var_dump($imageType);
if ($imageType == '.png'){
imagepng($dst_r,$name);
}
if ($imageType == '.jpg' || $imageType == '.jpeg'){
imagejpeg($dst_r,$name, 100);
}
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);
$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
Use PHP to determine what type of image it is, then dynamically use *_png functions instead of *_jpeg ones. IE, instead of imagecreatefromjpeg use imagecreatefrompng

imagecopyresampled resizes in chrome crops in ie/ff

i have come across the following problem. i have made an thumbnailer with gd and when i run it in chrome this is what it does:
this is exactly what i expected it to do(resize it)
screenshot taken in chrome
sadly this is what firefox and ie do:(crop it)
image taken in ff
i have the following code taking care of my resize:
// this image is created by another php file when text is filled in
$file = "hidden.png";
$size = GetImageSize($file);
if($size !== false){
$w = $size[0];
$h = $size[1];
//set new size
$nw = $_GET['width'];
$nh = ($nw*$h)/$w;
}
else{
//set new size
$nw = 400;
$nh = 200;
}
//draw the image
$src_img = imagecreatefrompng($file);
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);
//resizing the image
imagepng($dst_img);
imagedestroy($src_img);
imagedestroy($dst_img);
i have searched abit on stack and on google and the only thing i can find are solutions that are using css which i dont need since my image isnt constructed that way.
what do i need to do code-wise(not css related) to get it working correctly in all browsers?
if needed i can post more code
It has definitely nothing to do with the Browser, because that is not the way php works.
First of all the php-code gets interpreted on the server and then the result is past to the Client(Browser).
So in my opinion you should first check if the image generation is working correctly. Means that it produce every time the same Image. Then you should check this part:
if($size !== false){
$w = $size[0];
$h = $size[1];
$nw = $_GET['width']; // <---- For Debugging set here a static number
$nh = ($nw*$h)/$w;
}
Try to set for the debugging part, every variable which could change on each request to a fix value.
I hope i could help you
i solved the question by merging the above script with my allready existing script to generate the image.
/* Get image info */
if(!isset($_POST['width']) && !isset($_POST['height']))
{
$width = '200';
$height = '100';
}
else
{
$width = $_POST['width'] ;
$height = $_POST['height'];
}
$Image = imagecreatetruecolor($width,$height) ;
$sx = imagesx($Image) ;
$sy = imagesy($Image) ;
/*Check if RGB values have been set*/
if(!isset($_POST['r'])) { $R = 255; } else { $R = $_POST['r']; }
if(!isset($_POST['g'])) { $G = 255; } else { $G = $_POST['g']; }
if(!isset($_POST['b'])) { $B = 255; } else { $B = str_replace(")" , "" , $_POST['b']); }
/*Check if the text value is set */
if(!isset($_POST['text'])) {$Text = "Uw tekst hier";}
else if($_POST['text'] == '') {$Text = "Uw tekst hier";}
else {$Text = $_POST['text'];}
/*Check if the font is set */
if(!isset($_POST['font'])) {$Font="./Fonts/arial.ttf" ;}
else{$Font= "./fonts/".$_POST['font'].".ttf";}
$FontColor = ImageColorAllocate ($Image,$R,$G,$B) ; //TextColor
$FontShadow = ImageColorAllocate ($Image,0,0,0) ; //BackGroundColor
$Rotation = 0 ;
/* Iterate to get the size up */
$FontSize=1 ;
do
{
$FontSize *= 1.1 ;
$Box = #ImageTTFBBox($FontSize,0,$Font,$Text);
$TextWidth = abs($Box[2] - $Box[6]) ;
$TextHeight = abs($Box[3] - $Box[7]) ;
}
while ($TextWidth < $sx*0.94) ;
/* Awkward maths to get the origin of the text in the right place */
$x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2;
$y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
imagefilledrectangle($Image, 0, 0, $sx , $sy , $FontShadow);
ImageTTFText ($Image,$FontSize,$Rotation,-$Box[6] ,-$Box[7],$FontColor,$Font,$Text);
if(isset($_POST['resize']) && $_POST['resize'] == 1)
{
$nw = 400;
$nh = 200;
$src_img = $Image;
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $sx, $sy);//resizing the image
imagepng($dst_img, "hidden.png");
imagedestroy($src_img);
imagedestroy($dst_img);
}
else
{
//header('Content-type: image/png');
Imagepng($Image, "hidden.png") ;
}

Resizing pictures with preserving quality php

I using following method to resize image:
private function newDim($maxHeight, $maxWidth, $height, $width) {
if(($width / $height) >= ($maxWidth / $maxHeight)){
$nw = $maxWidth;
$nh = $height * ($maxWidth / $width);
$nx = round(abs($maxHeight - $nh) / 2);
$ny = 0 ;
}else {
// by height
$nw = $width*($maxHeight/$height);
$nh = $maxHeight;
$nx = 0;
$ny = round(abs($maxWidth - $nw) / 2); ;
}
return array($nw,$nh,$nx,$ny);
}
After that I want to save this image. For this case I using this method:
public function upload($file_param_name) {
$file_name = $_FILES[$file_param_name]['name'];
$source_file_path = $_FILES[$file_param_name]['tmp_name'];
$$this->ext = pathinfo($file_name, PATHINFO_EXTENSION);
$ext = 'jpg';
$this->ext = $ext;
$ext =strtolower($ext);
$new_file_name = $file_name."-".md5(uniqid(rand(), true));
$this->image_hashname = $new_file_name;
$target_path = $this->store_folder.basename($new_file_name);
list($width,$height,$type)=getimagesize($source_file_path);
switch ($type) {
case 1: // gif -> jpg
$src = imagecreatefromgif($source_file_path);
break;
case 2: // jpeg -> jpg
$src = imagecreatefromjpeg($source_file_path);
break;
case 3: // png -> jpg
$src = imagecreatefrompng($source_file_path);
break;
}
$th = 240;
$tw = 240;
list($nh,$nw,$nx,$ny) = $this->newDim($th, $tw, $height, $width);
$tmp=imagecreatetruecolor($tw,$th);
$white = imagecolorallocate($tmp, 255,255,255);
imagefill($tmp, 0, 0, $white);
imagecopyresized($tmp,$src,$ny,$nx,0,0,$nh,$nw,$width,$height);
$thmbfile = $this->store_folder.basename($new_file_name."-thumb.".$ext);
imagejpeg($tmp,$thmbfile,100);
imagedestroy($src);
imagedestroy($tmp);
}
When I save image with sizes 300x300 to 240x240 the quality of new image is very poor. Where I'm wrong?
The images :
OLD: http://cbn-design.eu/imgs/original.jpg
NEW: http://cbn-design.eu/imgs/new.jpg
As per this answer, try using imagecopyresampled() instead of imagecopyresized().

help needed to resize an image in php

I have a bit of code that generates thumbnails from an uploaded image. The only problem is that it cuts portrait images off, rather than resizing the portrait image to fit the height of the thumbnail, landscape images are fine. I was wondering if anyone could help me out to change the code so it will place portrait images inside the thumbnail properly? (if that makes sense?)
Here's the code:
$setSize = 150;
$setHSize = 113;
$jpeg_quality = 75;
list($width, $height, $type, $attr) = getimagesize($origPath);
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
$img_r = imagecreatefromjpeg($origPath) or notfound();
$dst_r = ImageCreateTrueColor( $setSize, $setHSize );
$heightOffset = round( ($setHSize-$newH)/2 );
$white = imagecolorallocate($dst_r, 255, 255, 255);
imagefilledrectangle($dst_r, 0, 0, $setSize, $setHSize, $white);
imagecopyresampled($dst_r, $img_r, 0, $heightOffset, 0, 0, $newW, $newH, $width, $height);
header("Content-type: image/jpeg");
imagejpeg($dst_r, $thbPath, $jpeg_quality);
I just don't fully understand the way php creates images, so any help would be appreciated :)
The way you compute $newW and $newH is incorrect for what you want. You are giving preference to the width, so most landscape images will look okay, but portrait will be cut off. Try the following instead:
// assume landscape and see how things look
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
if ($newH > $setHSize) {
// portrait image
$newH = $setHSize;
$newW = round( $width * ( $setHSize / $height ) );
}
I hope this helps!
Hope this helps.
<?php
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
include_once(DOCROOT."/dbc.php");
//**********************| Resize based on height
$photo_height = 350;
//**********************| Get the file from the post
$file = $_FILES['file'];
$path_thumbs = (DOCROOT."/gallery/");
$path_big = (DOCROOT."/trash/");
//**********************| Check permission
if (!is_writeable($path_thumbs)){
die ("Error: The directory <b>($path_thumbs)</b> is NOT writable");
}
if (!is_writeable($path_big)){
die ("Error: The directory <b>($path_big)</b> is NOT writable");
}
//**********************| Make sure you have a file
if (isset($file)){
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//**********************| Make new name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//**********************| See the kind of file we have
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}
elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}
elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//**********************| Get the height and width
list($width, $height) = getimagesize($file_tmp);
$imgratio=$height/$width;
if ($photo_height >= $height){
//*********** Dont resize if the image is smaller then $photo_height = 350;
$newwidth = $width;
$newheight = $height;
}
elseif ($imgratio>1){
$newheight = $photo_height;
$newwidth = $photo_height/$imgratio;
}
else{
$newwidth = $photo_height;
$newheight = $photo_height*$imgratio;
}
if (function_exists(imagecreatetruecolor)){ $resized_img = imagecreatetruecolor($newwidth,$newheight); }
else{ die("Error: Please make sure you have GD library ver 2+");
}
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext",'100');
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
$newimage = "$rand_name.$file_ext";
}
else {
echo "Sorry, there was a problem, Please try again.\n\n";
}
adaptiveResizeImage
or
adaptiveCropThumblanil
in Imagick can help you

Categories