imageflip() in PHP is undefined - php

Whenever I am trying to use the function imageflip(), it shows me the following message
Fatal error: Call to undefined function imageflip() in D:\xampp\htdocs\temp1\image_flip.php on line 6
Once I have called the imap_open function, even though, I already installed the imap extension and configured all. However, it still shows the same message.

imageflip() is only available after PHP 5.5. However, you can still define it yourself, as explained here (although if you plan to upgrade to PHP 5.5, it is not recommended to implement yours, or at least change the name to avoid duplication problems). For the sake of stackoverflow, I'll paste the code here:
<?php
/**
* Flip (mirror) an image left to right.
*
* #param image resource
* #param x int
* #param y int
* #param width int
* #param height int
* #return bool
* #require PHP 3.0.7 (function_exists), GD1
*/
function imageflip(&$image, $x = 0, $y = 0, $width = null, $height = null)
{
if ($width < 1) $width = imagesx($image);
if ($height < 1) $height = imagesy($image);
// Truecolor provides better results, if possible.
if (function_exists('imageistruecolor') && imageistruecolor($image))
{
$tmp = imagecreatetruecolor(1, $height);
}
else
{
$tmp = imagecreate(1, $height);
}
$x2 = $x + $width - 1;
for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--)
{
// Backup right stripe.
imagecopy($tmp, $image, 0, 0, $x2 - $i, $y, 1, $height);
// Copy left stripe to the right.
imagecopy($image, $image, $x2 - $i, $y, $x + $i, $y, 1, $height);
// Copy backuped right stripe to the left.
imagecopy($image, $tmp, $x + $i, $y, 0, 0, 1, $height);
}
imagedestroy($tmp);
return true;
}
And to use it:
<?php
$image = imagecreate(190, 60);
$background = imagecolorallocate($image, 100, 0, 0);
$color = imagecolorallocate($image, 200, 100, 0);
imagestring($image, 5, 10, 20, "imageflip() example", $color);
imageflip($image);
header("Content-Type: image/jpeg");
imagejpeg($image);
I haven't tried it, and the code isn't mine at all, but with some tricks you could adapt it to your needs.

Related

PHP Image: generated image has right and bottom black border on production server, but not on my local machine

This app is written by me, I've tested it on my local machine, and the image generated by my app is great without bug on my local development server machine.
My app is an API, the user use it to generate tiled image. It mostly uses PHP Image GD library.
The issue: Generated image has one-pixel-width right and bottom black borders, but it only happen on production server, it doesn't on my local server. The border is only generated when the image is a transparent one (in my case: 'outline', 'invert', 'black' image type. Look at the code below). But sometimes the border is there mostly and sometimes it's not.
I'm very sure that there is nothing wrong with my code and my app is working flawlessly. I have tested on both environments with the same image type, same dimension, supplied with the same configuration for my app... and still, the production server generates image that has the border.
Here is a piece of code of my app to look suspiciously at:
$src = $img->filePath;
$src_outline = $img->filePathComplements['outline'];
$src_invert = $img->filePathComplements['invert'];
$src_black = $img->filePathComplements['black'];
$info_text = is_array($img->info) ? join($img->info, ', ') : (is_string($img->info) ? $img->info : '');
$w = $img->widthOriginal;
$h = $img->heightOriginal;
$x = $img->fit->x + $this->packer->getPageMarginLeft() + $this->packer->getMarginLeft() +
$this->packer->getVerticalBorderWidth() + $this->packer->getVerticalBordefOffset();
$y = $img->fit->y + $this->packer->getPageMarginTop() + $this->packer->getMarginTop();
$info_y = $y + $h + $this->packer->getImageInfoMargin();
// Create main and complement images
$image_main = imagecreatefrompng($src);
$image_outline = imagecreatefrompng($src_outline);
$image_invert = imagecreatefrompng($src_invert);
$image_black = imagecreatefrompng($src_black);
list($w_px_original, $h_px_original) = getimagesize($src);
$image_main_resampled = Image::imageCreateTrueColorTransparent($w, $h);
$image_outline_resampled = Image::imageCreateTrueColorTransparent($w, $h);
$image_invert_resampled = Image::imageCreateTrueColorTransparent($w, $h);
$image_black_resampled = Image::imageCreateTrueColorTransparent($w, $h);
// Resample images from original dimension to DPI-based dimension
imagecopyresampled($image_main_resampled, $image_main, 0, 0, 0, 0, $w, $h, $w_px_original, $h_px_original);
imagecopyresampled($image_outline_resampled, $image_outline, 0, 0, 0, 0, $w, $h, $w_px_original, $h_px_original);
imagecopyresampled($image_invert_resampled, $image_invert, 0, 0, 0, 0, $w, $h, $w_px_original, $h_px_original);
imagecopyresampled($image_black_resampled, $image_black, 0, 0, 0, 0, $w, $h, $w_px_original, $h_px_original);
// Add image to all containers
// Parameters are: Destination image, source image, destination starting coordinates (x, y),
// source starting coordinates (x, y), source dimension (width, height).
imagecopy($container_main, $image_main_resampled, $x, $y, 0, 0, $w, $h);
imagecopy($container_outline, $image_outline_resampled, $x, $y, 0, 0, $w, $h);
imagecopy($container_invert, $image_invert_resampled, $x, $y, 0, 0, $w, $h);
imagecopy($container_black, $image_black_resampled, $x, $y, 0, 0, $w, $h);
// Add info to main and outline images
$info = Image::imageDrawTextBordered($w, $info_h, INFO_FONT_SIZE, INFO_BORDER_SIZE, $info_text);
imagecopy($container_main, $info, $x, $info_y, 0, 0, $w, $info_h);
imagecopy($container_outline, $info, $x, $info_y, 0, 0, $w, $info_h);
And Image::imageCreateTrueColorTransparent() is:
/**
* Creates and returns image resource of a true color transparent image.
* #param $width
* #param $height
* #return resource
*/
public static function imageCreateTrueColorTransparent($width, $height) {
$im = imagecreatetruecolor($width, $height);
imagealphablending($im, false);
imagesavealpha($im, true);
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);
return $im;
}
The example of result from my local machine (click to view in original size):
The example of result from the production server (click to view in original size):
I've been doing some research here on Stackoverflow, and I got this two threads who said that the issue was generated by imagecopyresampled() function. Still, I'm not so sure about this, since my app is working flawlessly on my local machine. This is the list of the discussion threads:
imagecopyresampled issue – black border right and bottom …
PHP imagecopyresampled() produces image border on one side
Any help would be appreciated, please elaborate if you know what's causing this and/or you've ever experienced this. Thank you in advance.
This function resizes an image regardless of its format or the presence of alpha channel/transparency.
To avoid the problem due to resampling, a padded version of the original image is created so that the column of pixels farthest to the right and the row of pixels below have sufficient data to display the colors correctly.
The size of the padding is calculated independently for the two axes based on the difference in size between the original image and the resized image.
For example, an image of 256x128 pixels which must be resized to 16x16 pixels requires the following padding:
256 / 16 = 16 columns on the right
128 / 16 = 8 rows on the bottom
this is because the color of each pixel of the resized image will be calculated on a rectangle of 16x8 pixels of the original image (in the simplest case of a bilinear filtering).
/** Resize an image resource.
*
* #param resource $src_image Original image resource.
* #param int $dest_x Destination image x position.
* #param int $dest_y Destination image y position.
* #param int $dest_width Destination width.
* #param int $dest_height Destination height.
* #param int $src_width Source width (can be less than full-width to get a subregion).
* #param int $src_height Source height (can be less than full-height to get a subregion).
* #return false|resource Resized image as resource, false on error.
*/
function resize_resource($src_image, $dest_x, $dest_y, $dest_width, $dest_height, $src_width, $src_height) {
$img_width = imagesx($src_image);
$img_height = imagesy($src_image);
// Create a padded version of source image cloning rows/columns of pixels from last row/column
// to ensure full coverage of right and bottom borders after rescaling.
// Compute padding sizes.
$pad_width = (int)ceil($img_width / $dest_width);
$pad_height = (int)ceil($img_height / $dest_height);
$padded = imagecreatetruecolor($img_width + $pad_width, $img_height + $pad_height);
if ($padded === false) return false;
imagealphablending($padded, false);
$transparent = imagecolorallocatealpha($padded, 0, 0, 0, 127);
imagefill($padded, 0, 0, $transparent);
imagecopy($padded, $src_image, 0, 0, 0, 0, $img_width, $img_height);
// Clone last column.
for ($i = 0; $i < $pad_width; ++$i)
imagecopy($padded, $src_image, $i + $img_width, 0, $img_width - 1, 0, 1, $img_height);
// Clone last row.
for ($i = 0; $i < $pad_height; ++$i)
imagecopy($padded, $src_image, 0, $i + $img_height, 0, $img_height - 1, $img_width, 1);
// Fill remaining padding area on bottom-right with color of bottom-right original image pixel.
$pad_pixel = imagecolorat($padded, $img_width - 1, $img_height - 1);
$pad_color = imagecolorallocatealpha($padded, ($pad_pixel >> 16) & 0xFF,
($pad_pixel >> 8) & 0xFF, $pad_pixel & 0xFF, ($pad_pixel >> 24) & 0x7F);
imagefilledrectangle($padded, $img_width, $img_height,
$img_width + $pad_width - 1, $img_height + $pad_height - 1, $pad_color);
// Create new rescaled image.
$new = imagecreatetruecolor($dest_width, $dest_height);
if ($new === false) return false;
imagealphablending($new, false);
$transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);
imagefill($new, 0, 0, $transparent);
imagecopyresampled($new, $padded, 0, 0, $dest_x, $dest_y, $dest_width, $dest_height, $src_width, $src_height);
return $new;
}
NOTE: for a correct transparency display in the final image it is necessary to correctly use the following code just before writing it to disk:
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagecolortransparent ($img, $transparent);
in the case of indexed-color images, or the following code:
imagesavealpha($img, true);
in the case of images with alpha channel. Where $img is the resized image resource returned by the function above.
This method allows you to resample even small images without creating an offset with respect to the original image.

Gd Library Flip image and saving it

I am using PHP GD library to flip an image and then save that flipped image. However I am able to flip image successfully but I don’t know how to save it with another name in a folder. My code is
$filename = '324234234234.jpg';
header('Content-type: image/jpeg');
$im = imagecreatefromjpeg($filename);
imageflip($im, IMG_FLIP_VERTICAL);
imagejpeg($im);
You need to pass a second parameter to imagejpeg($im) call with the path to the file you want to store.
imagejpeg($im, 'path/to/new/file.jpg');
http://php.net/manual/en/function.imagejpeg.php
Look at the documentation for imagejpeg where it explains the second parameter relates to $filename:
bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
So just add the new filename as a second parameter like this; assuming the name of the new name is new_filename.jpg. Also comment out or completely remove the header line so you are not outputting the image to the browser, but rather saving it to a file so the header isn’t needed:
$filename = '324234234234.jpg';
// header('Content-type: image/jpeg');
$im = imagecreatefromjpeg($filename);
imageflip($im, IMG_FLIP_VERTICAL);
imagejpeg($im, 'new_filename.jpg');
Also note that while imageflip is nice to use it is only available in PHP 5.5 & higher; it won’t be available in PHP 5.4 or lower:
(PHP 5 >= 5.5.0)
image flip — Flips an image using a given mode
So if you want to use it in PHP 5.4 or lower, you need to create the logic to flip it on your own in the code or use a function like this. It only flips horizontally so you would have to adjust it to flip vertically, but posting here so you have something to explore & work with if needed:
/**
* Flip (mirror) an image left to right.
*
* #param image resource
* #param x int
* #param y int
* #param width int
* #param height int
* #return bool
* #require PHP 3.0.7 (function_exists), GD1
*/
function imageflip(&$image, $x = 0, $y = 0, $width = null, $height = null)
{
if ($width < 1) $width = imagesx($image);
if ($height < 1) $height = imagesy($image);
// Truecolor provides better results, if possible.
if (function_exists('imageistruecolor') && imageistruecolor($image))
{
$tmp = imagecreatetruecolor(1, $height);
}
else
{
$tmp = imagecreate(1, $height);
}
$x2 = $x + $width - 1;
for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--)
{
// Backup right stripe.
imagecopy($tmp, $image, 0, 0, $x2 - $i, $y, 1, $height);
// Copy left stripe to the right.
imagecopy($image, $image, $x2 - $i, $y, $x + $i, $y, 1, $height);
// Copy backuped right stripe to the left.
imagecopy($image, $tmp, $x + $i, $y, 0, 0, 1, $height);
}
imagedestroy($tmp);
return true;
}

Captcha renders as broken text instead of image using PHP & GD

I am using this Kohana Captcha module in an application. The image renders correctly on my local environment but on our dev environment it returns the following:
�PNG
IHDR 2 1îµM JIDATxÕ|il¤ÉyÞSUßÙýõÅr8$ç¾8«Ñ=¼YÁ¶àݵ9 È°£ÀH #üÌß $#¤ÀFäì$¬X²VÒÚÒjiµëÕÜË!Co²}~gùÑMvl»I$¿`_W}u
¤YZúHPÝ©²Vq×ÝG4øÅ5tªëÕÏN%*v6óB^ï¢kT×A (Å]ïç²m¶Þ^HåsáEÜã\Hµïq5 ni©#)Bé£ûÄ»¥àåsýí5
ª±êgáùØelCóBQý,#¡¤b¦ #QãÚN¶¦o¾pµâEBÚºfk©1ÒlFIÜ qCÀ¥ô¢ªM4µÍFLO¤#Éæo:&ïv¤T~Áoo´C"jè±êÌMánoÌj(*.¥ôqS¿SàB*ð0¥1[×l]3Xsö`:u])¢¥¸heÜFÜHö' !g¹¼Vvs} ÒE§ÛQ~ñ"Ñѵê4M¢ßDxî¤F!?[c¨î^(ä6ÁèEÂ0BlÙºfiLk&í`2f2¤R^ÄC!wZS
¦c¤ Ù<d>xÅ#$ûÍúD¯#¥
J{0Áa3êBñ½:Ô©]ÕYÖÀ»
C®T)à¥Ð)Ý6cbi¥iËJùp£Èço=RÐL]mj¥ËåF é|$z£ìK¤
Êa»kÞ1ÓT ÀýÀ0Xë};a#BBüH§t0tcJHÌÐb Ò¸ s© )ÒjÄ2¶Rª¸TòÛ¹Ê]÷èq½$ûùbXyì(FÁhuwdÈlÇ!#DßRð¢ö$µ©±sSª© ¥ ÓH¨*N­*¾KËe(^´Tts!ÄéjrX!éäú\!r[RKû&ªëªZÑn&è®ôØ Ô(áBVuµmRÚ¶snE?,xaUÒÚFs£¶ª8뼸\~ôHå5Ä;cM¾#$}$µþ0ym(§ö ¤vÒ! PñDÌjIº~KÖÝþÈçrv½¢SjÕ.¦ÆvBè˺â4µuÍÖ©±mpjmWZ© w4AL­Ï"ÿ± Hj$e}ZAñ±â·I¡¡·«Ý¸lÇ SÂÈvòÆó`jÌÖYÌÐÆiB ÅåâÜù¡4=ÊÍxpø(Ò¯KÉ-'ýÑ(¶a÷Çá56R¼ê, ðê¡?Ú5\£6\R[×Ú#a±;míüPJåfó<h>
g(Çz-3m0*©¢¯,ûù»%wEÔ!TÛm'âv+^kÓ `I#
CxÑM²§qòÖ-cXö&ÖlZ¡Pø~ _(ÀN6A2Jeg
"Ü{û´K9éÌñDj4ÎÌÝiUο·:ÿjpa7©ìnG±Eü¨¡S]#¤v,¥`LµÙûåLJ±Åß6s51G[tKª¤í;N/B­±ó+¦±ÎátöA^DMtÝm¦;ô Ç°7CêJªÊ²_YôÜ%_D2ë53'FB`wÇ_x®ëö{P©4ve»*ÚciUɹ3¦ÏLóÃ:ýÝ?|/ôµw{fïv¯Í§mgIoi[Æ6,;ô}!UÀUë¸ì«{XÌ%¢H5Úq4½ö /y}[©N^ø·ãVf{ûo­¬\Ëçï¢J³ßóÌñ/I¦ ĺ­ËtrâOg¾5¿'ÁLÆ"/hÍvCÁA}¤DÆMwW ô.ÿ{^E_îê_î
}­o:5·²¥±3ç.d^!Ðm5F¬áµ¢|±
Ù[ÂáhÕç÷¿»¸|u]Í'^Yô¾µbuZÉá8 BIçTá~Ù]nQÎÿý+g_¦ëìÓß¡Fä"äJ*îJaKÉÅ]ÉããóGO­.LwÌLô±ÈIÂðéùsO:0ºd9~L&¢`2â/x¡ÏÛ°lÙé³W®í8P (£¦cºù`óX-¾üÅrfRï8]ÚùhõzáQc(ä&\ÍféQ !¤{àÌkOÿôkYZ*h¶Ùy¼ô¥óO:Ý)Ý6Eñ×#"Bet øÙWÜß<y>c:'='íö]ö/8©
eÒ¯^)°V ÚJHnRv¦pü³]BQÇj&ëåÚ¦äî6ÛdN8{NC
y÷[óÉxfÔ Çõ_¼ñ¦[¤ÓÜÀËÃrPÏÎrÉý Þ|î_¼:ðÄ(Ð
ë¹láájq!§cr¿v
ÓÄÀhNIÌ~Ú]]]a-~cmdòÆyÊÄÀÈòÈèúÈ°``ty`t
ë+ÎÂl"®-¤ÚèÔr!ÓpåÌç^tFⶣ¯,ÛäÓ¨7ܼßSPäc¿Õ_McIÝþNÔÃcËd÷b JcÅiwð.B#CöâٰتïNÊHd§$Kr(X©øÑgOpsåüûïDAëJôÿü¥®GôêÄ|Û; Hvº#çkñ?i|¦Å\¢²8¸4ytéAW¶(Uf,%ÂÎÅÓW>=ûôL¦·TÌÆÜòÞe ìôÁ ì4¾øÞ¡QiÄ ¢XRKsM¬ ¦S#¦»ëuKFjàN3© ø·¤RT×ÂOÅ{­j/ñµÅ§ê¯WrSKÃ×NSßÅáîSG ¬|2·xí»R(>¾¯ÚÑLõá*Æ÷F&¯÷K¾]ÅDAQ_Ú¡D¾<k>¼]¨KÁõ·VB¯jPª>©r #¦wK5¾u°ÍÓª%pAvíN
%¹R
³o¯Õú(ÒÿdmýK멾l}z¥:R\2CÏÏ®}¿?ôõ¦Ï5J¹ø߯øf,¸òÚíu Ró HAÞý3óS­±O]ØÓoüÆ;W£ÿùõñ§ºA¬.³¡aÉîÕ·§¤®3:F'óÕ'Áx%Yð¤Õ(~NJrA©ý¤Ä¡Ým'ìâìþ«x2ÃÝÕ¹«Õ­à~¤k¤v­ÜS Ô0øaÇklU×ØÕ_|òó÷LP,Q^YÿÁ7ìjñUmCH(ýµÔùËοúÄ#IB(¡|ìTÙBÇpmEB´ÅNv¬N΢î'¬Z. pQu]'kØJdN§3ûÐÎÄ­T#ä¥Å|} /b¶1ÿÑTq!¯oÏQk,AaäÜòÅÏÍZ{»Ð¼µÄ_þË­ÈÏMÒ2B ÈÑR6]}ú¾ÜËFÿãk+¿ä$S©ù§·]¥Ðp ¬
ZÑ¿Ý{³F÷±9¯Eë¯s-£ 1ª
Ñl=oÜd×D$γ^
B 1䵯Àtf¤&EsÓ+Ã)B Z ¥!j·è/Ý>½Úøpr"ùÆæQ¥ØäÂ{ HðÌK©'I¼õÝÜĹaYÚSÏg¥#W¢æHæÜø#,¦×GM1RB¬¤¡+A8hOÖüÉ`Ò[×+Õ?bÂý0«4_?VZgUöÛ)E«+¥zm[RÜ
3þÒ':z´
·?ÅÎý¿ÓY.ÿþ*e ض><fw> ¢HÞørçF^)Dàå¨RÒÃNL7^}#ÑŤß'L>âÉZØ1Ô^:ø±>Ó|¾
"^¶®IA5tÑ~§ê\¨Ç¬ÍJ0pyØån½Gó_úʽQF¡öî?½×+Õä>^¸-ÌÝ$´zúbìåW3ï|?ëj?¥$Ó Á¥gjáënÒ¨åÀ¢HDaÕ
'"TÙJjØIÚö&B#©iTËæ²^Êz)moY6ëÊ©DÀe·-¹3tÉ¥Ú½R¯ÉÊM=Ñ ¹XÍVf±f¡8ÜrásO?|ùwnÚA/6dsq=ñ£7*P0BÁ*m1gJ~=ýp:ª9æÛÖ¤;µá1RêÁ-©¤T¾·=Kù2?Sé>éÐôzMÛE\
¢!¡Ë¢)u3ÒAeV~" züôn(ʨÎpA¾6"³î­+Å̱îj¢0¿^ͨhA7²wRHîfA¡òÅ/Þyâ(PQsØ>è{ï¯.G Jµ¯­:9Ú¤À7þxùòç¿û}ïWRZ_U Â¥§jleþ~TZa¸É|Ûô"÷ö3KFmk¤P³®;ôд
Ø °t*Z{·®!v[O¼ÏP#~Æ­µ"ÙfTÙµ2uÖavjE)hA6}%TT9L/¯}õêàñ *,(àÆG'¯}p¶ÚKTK÷aõ¿,iRAüøü{U2þê?è øàÍR ¬ÀR#TÅ/qÔ`F¨É(¦ ¥û0´t ÄFúBlõ:»1bf,FT PtåF©Á!ZÌj;F6 ^Õba5ý'¹äîaâ×}¤ðÛðQ²£¦G(·yDßûáåÉ#m*T
I5½sf
õ²¢GPªÛûÞX;mæ9çó¯g4 Xfîr÷-ÛÜß°$³º![rîÞ|Ä$ÏXdëIÜy*©F®t D¬Ü)¹Ù­âf"d d»ªë.,A7ðÄáÊÏÓ~ý]×úùv×2ïû|!GWV
TBî?´îÚ&cUÀä7õ©÷ÿ²_ס J¥(æraoEQ*#q ~hÜù
P.ì>Ãt4¯!r½szÃ/wU#« n}sFDj[#A0Ë ~¸;¦;¡)B*Ùrà ßøö¨_xêó÷ÍNtßùöa a±Búkm½é}».MPLÀh¨uÅÊ祹ðõX|Ào¾ï¯Î7Y`øfCVÓÏGV®ó¨SÐÜ
²ÜìÒ À'c?.V׳dä·MÏé7/ýþPõóä÷VVoh¶Awd+)£4n)¡dÄ¥JV}!B¨ÆzNTSëÖ ¹ä^pµÂ¦½úÕGÎn 0}ôëo\èOiOâj#È?ëÒZOиÃV" yÎ ¥üwKï¿Uzçç_ê¼ô¼õæUv÷7P\Í=ËC :&6Göæ£#æ½êz,ï1ÿW'tX¾^¼ú'3ÕRiÞ¤jî׺"ÌFnxÌtö¾ôÏ>ÊôÔó-ö§ôÞb½Ún´7M£©þ_ÎÖÅÃû~w¯!Cqõý²RBõ£7×zSMïÍ b¦g«åB1 ~)5*#ºsaz¼Vj
©±¸ûó¶³R:¥Þû7SÞ¡34fj»ÝE ÙáN Pjéæ\+v­Óñ¥ßúýkUgqÝúÖ\^I°¶s¿Ë;u)ùà?ÿ»¥gíÏ^qRêÚß­w^Ê£ÈL(,\jAøÅUàR«OÓlr5SíM>:ó¥¾®Ó %Õíÿ½xãÍÓ°#Û°TRMþøÓc]#Ïg:%J)©2Ǻx$ÜlsùÑ.]yõîç¾p4pýÜTæÏÿø²[2èt{å¶T¨
£^þ½G·p£±,HJ¤:ñìËÉá1óç?+ðv©Rª[½é­(RØ_ ÝK÷Å ¤y'wóOs­C % µ¥ªµ$ÈutuwïîëÎÏåßýú[-¾¶)é&í«×N^Zn|xíÝ¡ïó¼µuebzoj{ÞäÌÚ~¸¼øk¿÷¯)%£7>q]ιʰg^J8gÿǽØxê(>¿* #çè¶N¿ÞÛq|K0TÙ{¹÷ó3ïäJ«ÈZ3µ^"øô³cg²
NÞü_ç~þöpcÁÛÙQë¼V×Jrcö(ÖuÖØ#Å7ªTëòß*¼ùÿ
JmyÃr¾ Ìö;3«c|­»ïDÊNÔðÖ¼¿p3?óaÎ_ßÜÜÃW6%*
¨¦×ØàØzàê÷owûn­n6f°£T DÆ'ª¾löÔ[Üpßß.µwgfº¶Ç^éR
ÑtÊRX^Ü¥0ðdà
/÷Øn»")ò¾öÓÄðéìñ+cçW:zÝÏÎ_xv^IÌO§§nöÌÝ9B|gÛ®H©Ü# ¿2ûÂk÷ÞÿþèþïÙvßBJë*h(Ú%µ:üÊ÷¯Ï¬Ü.ñK]u¥« #Æ4E¿«e'±©=S7{ dz*Ç/¬¿¸Ëk¿±Â×»¦3ó÷ÓÒQÀº!3v~ÀOºænJªáQ°átvüÓò]§%7=PSRÖÎåèa·~Ùt1½Qè¬~Î-Ç?\ùð¯G&Fή¿¸rñI%ùè¹ÕÑs«JµEgþ~úÆMSe-Û åyD§?é|¼r¾ëýÕsµßSªýy
ÀDÓQ 무Ä3¦n1 bã¡n5¹øó+Hã©,.&³×7P¬Ø½ë½S7z§ûd78?2ï,v)u)ùÍùRfãâÁ­ÎvK.ªÔ²iãs
¿6Të 8EÈD+Ù;M£U_òºUC?µT£¿ú§²Ü" Ûd 9ûNξóQ¿¦É¾áÂÀh.}n9Ýí9é À½=û[é1R%6ïO©]ÜM¿ÚN" `[µixHr_0R²
ÍúË¢ëùÎñtvóóαeyDç&3·o$þkoWùÄøòñ{×zö·Ò=¸sÅ6¢²¹IçhÛ (3Oò(qÊ ­a2ÉÆËçáøW®­w§³Mñ3¤cË>W
«ÎêóÓïí{è= #ilz£Íjýѽâ®
x #Ó¨®oR#5¤½bô·B ×Ö;)irM_gÄÐèÎE¼Ã9{#(¸Õ ¥DðöÆd"P¤ÉÒ*~ËÚ:ªÓh#o ¸ríÿ¾Ì/ú2VÂb#TQöyõG+l£EryS#íæ"i¡³0ØîÞäê fëlQuN5ä}
˾ÚÏ_ÅFq,ͱ´Þ åBgMtÍa± ZÐó8c¥ PJijó7Ô¾ fn
BP-clìËtë47­^©Üû·E04¢mMDè¤l
hb0ÁÔHÿUtéLU IEND®B`
This is the render() method:
public function render($html = TRUE)
{
// Creates $this->image
$this->image_create(Captcha::$config['background']);
// Add a random gradient
if (empty(Captcha::$config['background']))
{
$color1 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255));
$color2 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255));
$this->image_gradient($color1, $color2);
}
// Add a few random lines
for ($i = 0, $count = mt_rand(5, Captcha::$config['complexity'] * 4); $i < $count; $i++)
{
$color = imagecolorallocatealpha($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(100, 255), mt_rand(50, 120));
imageline($this->image, mt_rand(0, Captcha::$config['width']), 0, mt_rand(0, Captcha::$config['width']), Captcha::$config['height'], $color);
}
// Calculate character font-size and spacing
$default_size = min(Captcha::$config['width'], Captcha::$config['height'] * 2) / (utf8::strlen($this->response) + 1);
$spacing = (int) (Captcha::$config['width'] * 0.9 / utf8::strlen($this->response));
// Draw each Captcha character with varying attributes
for ($i = 0, $strlen = utf8::strlen($this->response); $i < $strlen; $i++)
{
// Use different fonts if available
$font = Captcha::$config['fontpath'].Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])];
// Allocate random color, size and rotation attributes to text
$color = imagecolorallocate($this->image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
$angle = mt_rand(-40, 20);
// Scale the character size on image height
$size = $default_size / 10 * mt_rand(8, 12);
$box = imageftbbox($size, $angle, $font, utf8::substr($this->response, $i, 1));
// Calculate character starting coordinates
$x = $spacing / 4 + $i * $spacing;
$y = Captcha::$config['height'] / 2 + ($box[2] - $box[5]) / 4;
// Write text character to image
imagefttext($this->image, $size, $angle, $x, $y, $color, $font, utf8::substr($this->response, $i, 1));
}
// Output
return $this->image_render($html);
}
and the image_render()
/**
* Returns the img html element or outputs the image to the browser.
*
* #param boolean $html Output as HTML
* #return mixed HTML, string or void
*/
public function image_render($html)
{
// Output html element
if ($html === TRUE)
return '<img src="'.url::site('captcha/'.Captcha::$config['group']).'" width="'.Captcha::$config['width'].'" height="'.Captcha::$config['height'].'" alt="Captcha" class="captcha" />';
// Send the correct HTTP header
Request::current()->headers('Content-Type', 'image/'.$this->image_type)
->headers('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
->headers('Pragma', 'no-cache')
->headers('Connection', 'close');
// Pick the correct output function
$function = 'image'.$this->image_type;
$function($this->image);
// Free up resources
imagedestroy($this->image);
}
GD library is enabled on the dev environment. Both environments use apache 2.2, php 5.4. Is there another server setting I need to enable?
This type of bugs sometimes bugs me, try to add:
die();
after the last line:
return $this->image_render($html);
Sometimes it works for me.
The text looks like a PNG datastream, only rendered by a text editor instead of an image viewer.

Image as isosceles trapezoid PHP GD

i have this function that transforms image to trapezoid using PHP GD:
function perspective($i,$gradient=0.9,$rightdown=true,$background=0xFFFFFF) {
$mult=3;
$w=imagesx($i);
$h=imagesy($i);
$image=imagecreatetruecolor($w*$mult,$h*$mult);
imagecopyresized($image,$i,0,0,0,0,$w*$mult,$h*$mult,$w,$h);
imagedestroy($i);
$w*=$mult;
$h*=$mult;
$im=imagecreatetruecolor($w,$h);
$background=imagecolorallocate($im,($background>>16)&0xFF,($background>>8)&0xFF,$background&0xFF);
imagefill($im,0,0,$background);
imageantialias($im,true);
$nh=$h-($h*$gradient);
for ($x=0; $x<$w; $x++) {
$ni=(($rightdown) ? $x : $w-$x);
$p=intval($h-(($ni/$w)*$nh));
if (($p%2)<>0)
$p-=1;
$nx=intval(($p-$h)/2);
imagecopyresampled($im,$image,$x,0,$x,$nx,1,$p,1,$h-1);
imageline($im,$x,$h-1,$x,$h+$nx,$background);
imageline($im,$x,0,$x,-$nx-1,$background);
}
imagedestroy($image);
imagefilter($im,IMG_FILTER_SMOOTH,10);
$i=imagecreatetruecolor($w/$mult,$h/$mult);
imageantialias($i,true);
imagecopyresampled($i,$im,0,0,0,0,$w,$h,$w*$mult,$h*$mult);
imagedestroy($im);
return $i;
}
But i cant modify it to produce isosceles trapezoid, i think there needs just one small modification, but i cant figure it outh (i tried lot of things).
Can someone help?
Right, basically that code should generate the right values, but due to a bug has a lot of cludges in place to get a trapezium shape. The bug is that the copy of each line has the destination-y and the source-y values transposed. The source-y should always be 0, the destination-y should change.
There were also a few other small numerical bugs and double rounding at unnecessary points throwing off the results.
Also, the variable naming was atrocious, so I have rewritten it so that the entire function is clear.
Try the following:
function makeTrapeziumImage($image, $gradient, $rightToLeft = false, $background = 0xFFFFFF, $supersampleScale = 3) {
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
$supersampledWidth = $originalWidth * $supersampleScale;
$supersampledHeight = $originalHeight * $supersampleScale;
$supersampledImage = imagecreatetruecolor($supersampledWidth, $supersampledHeight);
imagecopyresized($supersampledImage, $image,
0, 0, 0, 0,
$supersampledWidth, $supersampledHeight, $originalWidth, $originalHeight);
$workingImage = imagecreatetruecolor($supersampledWidth, $supersampledHeight);
$backgroundColour = imagecolorallocate($workingImage, ($background >> 16) & 0xFF, ($background >> 8) & 0xFF, $background & 0xFF);
imagefill($workingImage, 0, 0, $backgroundColour);
imageantialias($workingImage,true);
$endHeight = $supersampledHeight - ($supersampledHeight * $gradient);
for ($x = 0; $x < $supersampledWidth; $x++) {
$cX = ($rightToLeft ? $supersampledWidth - $x : $x);
$dstHeight = $supersampledHeight - ((($cX + 1) / $supersampledWidth) * $endHeight);
$dstY = intval(($supersampledHeight - $dstHeight) / 2) - 1; // -1 required as zero-indexed
$dstY = ($dstY < 0 ? 0 : $dstY); // Rounding can make $dstY = -1
$dstHeight = intval($dstHeight); // Round the height after calculating $dstY
imagecopyresampled($workingImage, $supersampledImage,
$cX, $dstY, $cX, 0,
1, $dstHeight, 1, $supersampledHeight);
}
imagedestroy($supersampledImage);
imagefilter($workingImage, IMG_FILTER_SMOOTH, 10);
$resizedImage = imagecreatetruecolor($originalWidth, $originalHeight);
imageantialias($resizedImage, true);
imagecopyresampled($resizedImage, $workingImage,
0, 0, 0, 0,
$originalWidth, $originalHeight, $supersampledWidth, $supersampledHeight);
imagedestroy($workingImage);
return $resizedImage;
}
The essential mechanism of the inner loop, as before, is to take each column of pixels, along the x-axis and resize them over a gradient. It naturally creates an isosceles trapezium. In order to create a non-isosceles trapezoid, another gradient would have to be specified. Alternatively, a set of start and end y-values could be specified and the gradients calculated from them.
Whilst this example works along the x-axis, in either direction as before, it could just as easily work along the y-axis (or the image could be rotated 90 degrees, processed, then rotated back).

How would I skew an image with GD Library?

I want to skew an image into a trapezoidal shape. The left and right edges need to be straight up and down; the top and left edges need to be angular. I have no idea what the best way to do this is.
I'm using GD Library and PHP. Can anyone point me in the right direction?
Thanks,
Jason
Try this:
<?
// Set it up
$img_name = "grid.jpg";
$src_img = imagecreatefromjpeg($img_name);
$magnify = 4;
// Magnify the size
$w = imagesx($src_img);
$h = imagesy($src_img);
$dst_img = imagecreatetruecolor($w * $magnify, $h * $magnify);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $w * $magnify, $h * $magnify, $w, $h);
$src_img = $dst_img;
// Skew it
$w *= $magnify;
$h *= $magnify;
$new_lh = abs($h * 0.66);
$new_rh = $h ;
$step = abs((($new_rh - $new_lh) / 2) / $w);
$from_top = ($new_rh - $new_lh) / 2 ;
$dst_img = imagecreatetruecolor($w, $new_rh);
$bg_colour = imagecolorallocate($dst_img, 255, 255, 255);
imagefill($dst_img, 0, 0, $bg_colour);
for ($i = 0 ; $i < $w ; $i ++)
{
imagecopyresampled($dst_img, $src_img, $i, $from_top - $step * $i, $i, 0, 1, $new_lh + $step * $i * 2, 1, $h);
}
// Reduce the size to "anti-alias" it
$src_img = $dst_img;
$dst_img = imagecreatetruecolor($w / $magnify * 0.85, $new_rh / $magnify);
imagecopyresampled ($dst_img, $src_img, 0, 0, 0, 0, $w / $magnify * 0.85, $h / $magnify, $w, $h);
header("Content-Type: image/jpg");
imagejpeg($dst_img);
?>
I found this thread (translated Dutch -> English) discussing the same thing. Looks like it might be what you're after. I think it's clear that you can't skew with GD without writing your own function to do so. If you have ImageMagick available, you might find this to be easier to achieve.
Good luck.
Make a nested loop for x = 0 to width and inside y = 0 to height, get pixel (rgba) at that coordinate, calculate new xy for skew rotation (using sine cosine, you have to have skew origin for angle calculation) and then copy pixels to empty image. Just high school math

Categories