Related
I am trying to copy image (to $img) after rotating image (many images $im) but I get weird behavior. Once I un-comment the line //$img = I only get the rotated image on my final output. Can I rotate the inner $im and copy it to final image$img?
<?php
$height = 80;
$width = 300;
$img = imagecreate($width, $height);
$c = imagecolorallocate ($img , 135, 135, 135);
imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));
for($i=0; $i<=5; $i++){
$im = imagecreatetruecolor(35, 35);
$gry = imagecolorallocate($im, 135, 135, 135);
$wht = imagecolorallocate($im, 255, 255, 255);
$j = mt_rand(0, 1);
$ch = mt_rand(0,1)?chr(rand(65, 90)):chr(rand(97, 122));
if($j == 0){
imagefill($im, 0, 0, $wht);
imagefttext($im, 20, 0, 3, 21, $gry, 'AHGBold.ttf', $ch);
//$img = imagerotate($im, mt_rand(0,10)-5, $wht);
}else{
imagefill($im, 0, 0, $gry);
imagefttext($im, 20, 0, 3, 21, $wht, 'AHGBold.ttf', $ch);
//$img = imagerotate($im, mt_rand(0,10)-5, $gry);
}
imagecopyresampled($img, $im, 5 + $i*42, $height/2 - 12, 0, 0, 40, 40, 25, 25);
}
header('Content-type: image/png');
imagepng($img);
change
$img = imagerotate($im, mt_rand(0,10)-5, $wht);
and
$img = imagerotate($im, mt_rand(0,10)-5, $gry);
to
$im = imagerotate($im, mt_rand(0,10)-5, $wht);
and
$im = imagerotate($im, mt_rand(0,10)-5, $gry);
in cases that imagerotes does not work you can use the following function to rotate an image:
function imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0)
{
$srcw = imagesx($srcImg);
$srch = imagesy($srcImg);
if($angle == 0) return $srcImg;
// Convert the angle to radians
$theta = deg2rad ($angle);
// Calculate the width of the destination image.
$temp = array ( rotateX(0, 0, 0-$theta),
rotateX($srcw, 0, 0-$theta),
rotateX(0, $srch, 0-$theta),
rotateX($srcw, $srch, 0-$theta)
);
$minX = floor(min($temp));
$maxX = ceil(max($temp));
$width = $maxX - $minX;
// Calculate the height of the destination image.
$temp = array ( rotateY(0, 0, 0-$theta),
rotateY($srcw, 0, 0-$theta),
rotateY(0, $srch, 0-$theta),
rotateY($srcw, $srch, 0-$theta)
);
$minY = floor(min($temp));
$maxY = ceil(max($temp));
$height = $maxY - $minY;
$destimg = imagecreatetruecolor($width, $height);
imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));
// sets all pixels in the new image
for($x=$minX;$x<$maxX;$x++) {
for($y=$minY;$y<$maxY;$y++)
{
// fetch corresponding pixel from the source image
$srcX = round(rotateX($x, $y, $theta));
$srcY = round(rotateY($x, $y, $theta));
if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
{
$color = imagecolorat($srcImg, $srcX, $srcY );
}
else
{
$color = $bgcolor;
}
imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
}
}
return $destimg;
}
function rotateX($x, $y, $theta){
return $x * cos($theta) - $y * sin($theta);
}
function rotateY($x, $y, $theta){
return $x * sin($theta) + $y * cos($theta);
}
I got the above code from a note in php.net
I've created a PHP script to generate an avatar. When I display the image, the dimensions are 250px x 250px. I want to resize at the end (when all the modifications has been done) the avatar before displaying it but I can not find the function.
This is my code :
if(!empty($_GET['pseudo']))
{
$query1 = $bdd->prepare("SELECT username, user_id, VID FROM phpbb_users LEFT JOIN 0php_users ON 0php_users.phpbb_id = phpbb_users.user_id WHERE username_clean = ?");
$query1->execute(array(strtolower($_GET['pseudo'])));
if($query1->rowCount() == 1)
{
$data1 = $query1->fetch();
$query2 = $bdd->prepare("SELECT nom FROM phpbb_user_group
RIGHT JOIN 0php_hubs ON phpbb_user_group.group_id = 0php_hubs.id_groupe
WHERE user_id = ?");
$query2->execute(array($data1['user_id']));
$data2 = $query2->fetch();
$image = imagecreatefrompng("avatar.png");
$background = imagecolorallocate($image, 0, 0, 0);
imagecolortransparent($image, $background);
imagealphablending($image, false);
imagesavealpha($image, true);
if(($_GET['param']=='ivao')&&(!empty($data1['VID'])))
{
$BoolIvao = true;
$ivao = imagecreatefrompng("http://status.ivao.aero/R/".$data1['VID'].".png");
imagecopy($image, $ivao, 87, 173, 0, 0, 150, 30);
}
$couleur = imagecolorallocate($image, 0, 0, 0);
$largeur_source = imagesx($image);
$fontfile = 'calibri.ttf';
$angle = 0;
$police = 18;
$text_size = imagettfbbox($police, $angle, $fontfile, 'Hub de '.$data2['nom']);
$text_size2 = imagettfbbox($police, $angle, $fontfile, $data1['username']);
$text_width = (($text_size[2] + $text_size[4]) / 2) - (($text_size[0] + $text_size[6]) / 2);
$text_width2 = (($text_size2[2] + $text_size2[4]) / 2) - (($text_size2[0] + $text_size2[6]) / 2);
$x = ($largeur_source - $text_width)/2;
$x2 = (176 - $text_width2)/2 + 74;
$y2 = ($BoolIvao == true)?160:175;
imagettftext($image, $police, $angle, $x2, $y2, $couleur, $fontfile, $data1['username']);
imagettftext($image, $police, $angle, $x, 35, $couleur, $fontfile, 'Hub de '.$data2['nom']);
imagepng($image);
$query2->closeCursor();
}
$query1->closeCursor();
}
Thanks
You need to use imagecopyresampled to resize image.
<?php
if(!empty($_GET['pseudo']))
{
$query1 = $bdd->prepare("SELECT username, user_id, VID FROM phpbb_users LEFT JOIN 0php_users ON 0php_users.phpbb_id = phpbb_users.user_id WHERE username_clean = ?");
$query1->execute(array(strtolower($_GET['pseudo'])));
if($query1->rowCount() == 1)
{
$data1 = $query1->fetch();
$query2 = $bdd->prepare("SELECT nom FROM phpbb_user_group
RIGHT JOIN 0php_hubs ON phpbb_user_group.group_id = 0php_hubs.id_groupe
WHERE user_id = ?");
$query2->execute(array($data1['user_id']));
$data2 = $query2->fetch();
$image = imagecreatefrompng("avatar.png");
list($width, $height) = getimagesize("avatar.png"); # get dimensions
$background = imagecolorallocate($image, 0, 0, 0);
imagecolortransparent($image, $background);
imagealphablending($image, false);
imagesavealpha($image, true);
if(($_GET['param']=='ivao')&&(!empty($data1['VID'])))
{
$BoolIvao = true;
$ivao = imagecreatefrompng("http://status.ivao.aero/R/".$data1['VID'].".png");
imagecopy($image, $ivao, 87, 173, 0, 0, 150, 30);
}
$couleur = imagecolorallocate($image, 0, 0, 0);
$largeur_source = imagesx($image);
$fontfile = 'calibri.ttf';
$angle = 0;
$police = 18;
$text_size = imagettfbbox($police, $angle, $fontfile, 'Hub de '.$data2['nom']);
$text_size2 = imagettfbbox($police, $angle, $fontfile, $data1['username']);
$text_width = (($text_size[2] + $text_size[4]) / 2) - (($text_size[0] + $text_size[6]) / 2);
$text_width2 = (($text_size2[2] + $text_size2[4]) / 2) - (($text_size2[0] + $text_size2[6]) / 2);
$x = ($largeur_source - $text_width)/2;
$x2 = (176 - $text_width2)/2 + 74;
$y2 = ($BoolIvao == true)?160:175;
imagettftext($image, $police, $angle, $x2, $y2, $couleur, $fontfile, $data1['username']);
imagettftext($image, $police, $angle, $x, 35, $couleur, $fontfile, 'Hub de '.$data2['nom']);
/* resize image */
$small_im = imagecreatetruecolor(250, 250);
imagecopyresampled($small_im, $image, 0, 0, 0, 0, 250, 250, $width, $height);
/* resize image */
imagepng($small_im);
$query2->closeCursor();
}
$query1->closeCursor();
}
this is the code I always use to resize an image through PHP (I hope it will help you) best wishes:
NOTE: $filetemp refers to your file's temporary name.
Also in this code i'm saving images as a png you can change it to your desired extension
<?php
$temporary = pathinfo($filename, PATHINFO_FILENAME);
$new_images = $temporary.".png";
$width=60; //*** Fix Width & Heigh (Autu caculate) ***//
$size=GetimageSize($filetemp);
$height=round($width*$size[1]/$size[0]);
$images_orig = ImageCreateFromJPEG($filetemp);
$photoX = ImagesX($images_orig);
$photoY = ImagesY($images_orig);
$images_fin = ImageCreateTrueColor($width, $height);
ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
imagepng($images_fin,"YourFolder/".$new_images);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
?>
I have set imagealphablending on every image I create, still there is a black background. What could be the problem?
$systemSettings = array(
'captcha' => array(
'colors' => array(array(30, 80, 180), array(20, 160, 40), array(220, 40, 10)),
'fonts' => array('AntykwaBold.ttf', 'Candice.ttf', 'Carbon.ttf', 'Duality.ttf', 'Heineken.ttf', 'Jura.ttf', 'StayPuft.ttf', 'TimesNewRomanBold.ttf', 'VeraSansBold.ttf'),
'size' => array('width' => '200', 'height' => '50')
)
);
function generateCaptcha() {
global $systemSettings;
$randomLetters = "abcdef";
$scale = 3;
$width = $systemSettings['captcha']['size']['width'];
$height = $systemSettings['captcha']['size']['height'];
$im = imagecreatetruecolor($width * $scale, $height * $scale);
imagealphablending($im, true);
//$GdBgColor = imagecolorallocate($im, 250, 250, 250);
//imagefilledrectangle($im, 0, 0, $width * $scale, $height * $scale, $GdBgColor);
$color = $systemSettings['captcha']['colors'][mt_rand(0, sizeof($systemSettings['captcha']['colors']) - 1)];
$GdFgColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
$fontfile = 'visual/fonts/' . $systemSettings['captcha']['fonts'][array_rand($systemSettings['captcha']['fonts'])];
$x = 20 * $scale;
$y = round(($height * 0.75) * $scale);
$length = strlen($randomLetters);
for ($i = 0; $i < $length; $i++) {
$degree = rand(-10, 10);
$fontsize = rand(20, 25) * $scale;
$letter = substr($randomLetters, $i, 1);
$coords = imagettftext($im, $fontsize, $degree, $x, $y, $GdFgColor, $fontfile, $letter);
$x += ($coords[2] - $x);
}
$k = rand(0, 100);
$xp = $scale * 12 * rand(1, 3);
for ($i = 0; $i < ($width * $scale); $i++)
imagecopy($im, $im, $i - 1, sin($k + $i / $xp) * ($scale * 5), $i, 0, 1, $height * $scale);
$k = rand(0, 100);
$yp = $scale * 12 * rand(1, 3);
for ($i = 0; $i < ($height * $scale); $i++)
imagecopy($im, $im, sin($k + $i / $yp) * ($scale * 14), $i - 1, 0, $i, $width * $scale, 1);
imagefilter($im, IMG_FILTER_GAUSSIAN_BLUR);
$imResampled = imagecreatetruecolor($width, $height);
imagecopyresampled($imResampled, $im, 0, 0, 0, 0, $width, $height, $width * $scale, $height * $scale);
imagealphablending($imResampled, true);
header("Content-type: image/png");
imagepng($imResampled);
imagedestroy($im);
imagedestroy($imResampled);
}
try this
$systemSettings = array(
'captcha' => array(
'colors' => array(array(30, 80, 180), array(20, 160, 40), array(220, 40, 10)),
'fonts' => array('AntykwaBold.ttf', 'Candice.ttf', 'Carbon.ttf', 'Duality.ttf', 'Heineken.ttf', 'Jura.ttf', 'StayPuft.ttf', 'TimesNewRomanBold.ttf', 'VeraSansBold.ttf'),
'size' => array('width' => '200', 'height' => '50')
)
);
function generateCaptcha() {
global $systemSettings;
$randomLetters = "abcdef";
$scale = 3;
$width = $systemSettings['captcha']['size']['width'];
$height = $systemSettings['captcha']['size']['height'];
$im = imagecreatetruecolor($width * $scale, $height * $scale);
// enable alpha blending on the destination image.
imagealphablending($im, true);
// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $im, 0, 0, 0, 127 );
imagefill( $im, 0, 0, $transparent );
// disable alpha blending on the destination image.
imagealphablending($im, false);
// save the alpha
imagesavealpha($im,true);
//$GdBgColor = imagecolorallocate($im, 250, 250, 250);
//imagefilledrectangle($im, 0, 0, $width * $scale, $height * $scale, $GdBgColor);
$color = $systemSettings['captcha']['colors'][mt_rand(0, sizeof($systemSettings['captcha']['colors']) - 1)];
$GdFgColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
$fontfile = 'visual/fonts/' . $systemSettings['captcha']['fonts'][array_rand($systemSettings['captcha']['fonts'])];
$x = 20 * $scale;
$y = round(($height * 0.75) * $scale);
$length = strlen($randomLetters);
for ($i = 0; $i < $length; $i++) {
$degree = rand(-10, 10);
$fontsize = rand(20, 25) * $scale;
$letter = substr($randomLetters, $i, 1);
$coords = imagettftext($im, $fontsize, $degree, $x, $y, $GdFgColor, $fontfile, $letter);
$x += ($coords[2] - $x);
}
$k = rand(0, 100);
$xp = $scale * 12 * rand(1, 3);
for ($i = 0; $i < ($width * $scale); $i++)
imagecopy($im, $im, $i - 1, sin($k + $i / $xp) * ($scale * 5), $i, 0, 1, $height * $scale);
$k = rand(0, 100);
$yp = $scale * 12 * rand(1, 3);
for ($i = 0; $i < ($height * $scale); $i++)
imagecopy($im, $im, sin($k + $i / $yp) * ($scale * 14), $i - 1, 0, $i, $width * $scale, 1);
imagefilter($im, IMG_FILTER_GAUSSIAN_BLUR);
$imResampled = imagecreatetruecolor($width, $height);
// enable alpha blending on the destination image.
imagealphablending($imResampled, true);
// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $imResampled, 0, 0, 0, 127 );
imagefill( $imResampled, 0, 0, $transparent );
// disable alpha blending on the destination image.
imagealphablending($imResampled, false);
// save the alpha
imagesavealpha($imResampled,true);
imagecopyresampled($imResampled, $im, 0, 0, 0, 0, $width, $height, $width * $scale, $height * $scale);
header("Content-type: image/png");
imagepng($imResampled);
imagedestroy($im);
imagedestroy($imResampled);
}
I made an image combining 3 different images, but I need a transparent background, and I don't succeed doing it. This is my final code:
<?php
$meko = $_GET['image'];
$im = $meko;
$bookback = "images/book_back.png";
$mekoCanvas = imagecreatetruecolor(115, 135);
$canvas = imagecreatetruecolor(115, 185);
$bookback = imagecreatefrompng($bookback);
$meko = imagecreatefromjpeg($meko);
imagecopy($mekoCanvas, $meko, 0, 0, 0, 0, 100, 135);
imagecopy($mekoCanvas, $bookback, 100, 0, 0, 0, 15, 135);
$im = $mekoCanvas;
$rH = 50; // Reflection height
$tr = 30; // Starting transparency
$div = 1; // Size of the divider line
$w = 115;
$h = 135;
//$im = imagecreatefromjpeg($im);
$li = imagecreatetruecolor($w, 1);
$bgc = imagecolorallocate($li, 255, 255, 255); // Background color
imagefilledrectangle($li, 0, 0, $w, 1, $bgc);
$bg = imagecreatetruecolor($w, $rH);
$wh = imagecolorallocate($im,255,255,255);
$im = imagerotate($im, -180, $wh);
imagecopyresampled($bg, $im, 0, 0, 0, 0, $w, $h, $w, $h);
$im = $bg;
$bg = imagecreatetruecolor($w, $rH);
for ($x = 0; $x < $w; $x++) {
imagecopy($bg, $im, $x, 0, $w-$x, 0, 1, $rH);
}
$im = $bg;
$in = 100/$rH;
for($i=0; $i<=$rH; $i++){
if($tr>100) $tr = 100;
imagecopymerge($im, $li, 0, $i, 0, 0, $w, 1, $tr);
$tr+=$in;
}
imagecopymerge($im, $li, 0, 0, 0, 0, $w, $div, 100); // Divider
header('content-type: image/jpeg');
imagecopy($canvas, $mekoCanvas, 0, 0, 0, 0, 115, 135);
imagecopy($canvas, $im, 0, 135, 0, 0, 115, 50);
imagejpeg($canvas);
imagedestroy($im);
imagedestroy($li);
?>
and the results is:
click here
You're not telling GD to use alpha in any of your code. That's done with imagesavealpha, imagealphablending, etc...
Try using
imagecolortransparent($im);
http://www.php.net/manual/en/function.imagecolortransparent.php
The PHP code below generates text as a dynamically created image, how would I be able to get the image to only be as large as the text? Thanks.
<?php
header('Content-Type: image/jpeg');
$text='Test';
$img = imageCreate(200,200);
imagecolorallocate($img, 255, 255, 255);
$textColor = imagecolorallocate($img, 0, 0, 0);
imagefttext($img, 15, 0, 0, 55, $textColor, 'bgtbt.ttf', $text);
imagejpeg($img);
imagedestroy($img);
?>
UPDATE 1: I found the answer here with the example of the original poster - Creating IMage from Text in PHP - how can I make multiline?
UPDATE 2: Martin Geisler's version also works well
When using a TrueType font, you use the imageftbbox function to obtain the bounding box for a string typeset with your font. The bounding box gives the offsets from the base-point to the four corners in the rectangle occupied by the text. So if you store the bounding box in $bb and use imagefttext to put text at ($x, $y), then the corners will have these coordinates:
($x + $bb[6], $y + $bb[7]) ($x + $bb[4], $y + $bb[5])
+-------+
| Hello |
+-------+
($x + $bb[0], $y + $bb[1]) ($x + $bb[2], $y + $bb[3])
That tells us that we want an image width of ($x + $bb[2]) - ($x + $bb[6]) = $bb[2] - $bb[6] and similarly an image height of $bb[3] - $bb[7]. The text should then be rendered at coordinates (-$bb[6], -$bb[7]) inside that picture since we want to have
(0, 0) = ($x + $bb[6], $y + $bb[7]) ==> $x = -$bb[6] and $y = -$bb[7]
You can try it out with this code. Put it into a file called img.php and browse to img.php?q=Hello to test:
<?php
header("Content-type: image/png");
$q = $_REQUEST['q'];
$font = "Impact.ttf";
$size = 30;
$bbox = imageftbbox($size, 0, $font, $q);
$width = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];
$im = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);
imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);
?>
If you use the bitmap fonts instead, then look at the imagefontwidth and imagefontheight functions.
#Martin Geisler's answer is almost correct, but I couldn't get my text to fit completely inside the image. I tried this instead, which works perfectly!
From the PHP Manual's User Contributed Notes:
$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";
$bbox = imagettfbbox($size, 0, $font, $text);
$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);
$image = imagecreatetruecolor($width, $height);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);
$x = $bbox[0] + ($width / 2) - ($bbox[4] / 2);
$y = $bbox[1] + ($height / 2) - ($bbox[5] / 2);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
$last_pixel= imagecolorat($image, 0, 0);
for ($j = 0; $j < $height; $j++)
{
for ($i = 0; $i < $width; $i++)
{
if (isset($blank_left) && $i >= $blank_left)
{
break;
}
if (imagecolorat($image, $i, $j) !== $last_pixel)
{
if (!isset($blank_top))
{
$blank_top = $j;
}
$blank_left = $i;
break;
}
$last_pixel = imagecolorat($image, $i, $j);
}
}
$x -= $blank_left;
$y -= $blank_top;
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);