Reputation: 73
I am having some issues with imagecopyresampled mostly that the image is not scaling correctly and that the position of the image is wrong and there is a black border around the edges.
I have the following vars set up
$tW = $width; // Original width of image
$tH = $height; // Orignal height of image
$w = postvar; // New width
$h = postvar; // New height
$x = postvar; // New X pos
$y = postvar; // New Y pos
And then run the following
$tn = imagecreatetruecolor($w, $h);
$image = imagecreatefromjpeg('filepathhere.jpeg');
imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH);
If anyone has any clues then that would be great help! Thanks
Upvotes: 2
Views: 1710
Reputation: 57316
There are several issues here. First, you shouldn't create the new image with the specified new height and width, but instead calculate what they should be based on the ratio of the original image, otherwise your scaled image will be distorted. For example, the code below will create a properly resized image that will fit into the given rectangle of $w x $h
:
$tW = $width; //original width
$tH = $height; //original height
$w = postvar;
$h = postvar;
if($w == 0 || $h == 0) {
//error...
exit;
}
if($tW / $tH > $w / $h) {
// specified height is too big for the specified width
$h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / $h) {
// specified width is too big for the specified height
$w = $h * $tW / $tH;
}
$tn = imagecreatetruecolor($w, $h); //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white;
//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will just create a scaled-down image
imagecopyresampled($tn, $image, 0, 0, 0, 0, $w, $h, $tW, $tH);
Now, if you want to copy only a certain portion of the original image, say from coordinates ($x, $y)
to the right-hand corner, then you need to include that into your calculation:
$tW = $width - $x; //original width
$tH = $height - $y; //original height
$w = postvar;
$h = postvar;
if($w == 0 || $h == 0) {
//error...
exit;
}
if($tW / $tH > $w / $h) {
// specified height is too big for the specified width
$h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / h) {
// specified width is too big for the specified height
$w = $h * $tW / $tH;
}
$tn = imagecreatetruecolor($w, $h); //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white;
//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will create a scaled-down portion of the original image from coordinates ($x, $y) to the lower-right corner
imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH);
If you give more details about what you're trying to achieve, I may be able to help further.
Upvotes: 3