Related
I'm creating a graph in fpdf and I saw this question and it is exactly the same as what I need but when I copied it on my report-weekly.php file it doesn't work and gave me an error message of
Notice: Undefined offset: 0 in C:\xampp\htdocs\qtqt\asd\report-weekly.php on line 112
Notice: Undefined offset: 1 in C:\xampp\htdocs\qtqt\asd\report-weekly.php on line 112
Notice: Undefined offset: 2 in C:\xampp\htdocs\qtqt\asd\report-weekly.php on line 112
FPDF error: Some data has already been output, can't send PDF file
this is the code I copied
<?php
require('diag/sector.php');
class PDF_Diag extends PDF_Sector {
var $legends;
var $wLegend;
var $sum;
var $NbVal;
function ColumnChart($w, $h, $data, $format, $color=null, $maxVal=0, $nbDiv=4)
{
// RGB for color 0
$colors[0][0] = 155;
$colors[0][1] = 75;
$colors[0][2] = 155;
// RGB for color 1
$colors[1][0] = 0;
$colors[1][1] = 155;
$colors[1][2] = 0;
// RGB for color 2
$colors[2][0] = 75;
$colors[2][1] = 155;
$colors[2][2] = 255;
// RGB for color 3
$colors[3][0] = 75;
$colors[3][1] = 0;
$colors[3][2] = 155;
$this->SetFont('Courier', '', 10);
$this->SetLegends($data,$format);
// Starting corner (current page position where the chart has been inserted)
$XPage = $this->GetX();
$YPage = $this->GetY();
$margin = 2;
// Y position of the chart
$YDiag = $YPage + $margin;
// chart HEIGHT
$hDiag = floor($h - $margin * 2);
// X position of the chart
$XDiag = $XPage + $margin;
// chart LENGHT
$lDiag = floor($w - $margin * 3 - $this->wLegend);
if($color == null)
$color=array(155,155,155);
if ($maxVal == 0)
{
foreach($data as $val)
{
if(max($val) > $maxVal)
{
$maxVal = max($val);
}
}
}
// define the distance between the visual reference lines (the lines which cross the chart's internal area and serve as visual reference for the column's heights)
$valIndRepere = ceil($maxVal / $nbDiv);
// adjust the maximum value to be plotted (recalculate through the newly calculated distance between the visual reference lines)
$maxVal = $valIndRepere * $nbDiv;
// define the distance between the visual reference lines (in milimeters)
$hRepere = floor($hDiag / $nbDiv);
// adjust the chart HEIGHT
$hDiag = $hRepere * $nbDiv;
// determine the height unit (milimiters/data unit)
$unit = $hDiag / $maxVal;
// determine the bar's thickness
$lBar = floor($lDiag / ($this->NbVal + 1));
$lDiag = $lBar * ($this->NbVal + 1);
$eColumn = floor($lBar * 80 / 100);
// draw the chart border
$this->SetLineWidth(0.2);
$this->Rect($XDiag, $YDiag, $lDiag, $hDiag);
$this->SetFont('Courier', '', 10);
$this->SetFillColor($color[0],$color[1],$color[2]);
$i=0;
foreach($data as $val)
{
//Column
$yval = $YDiag + $hDiag;
$xval = $XDiag + ($i + 1) * $lBar - $eColumn/2;
$lval = floor($eColumn/(count($val)));
$j=0;
foreach($val as $v)
{
$hval = (int)($v * $unit);
$this->SetFillColor($colors[$j][0], $colors[$j][1], $colors[$j][2]);
$this->Rect($xval+($lval*$j), $yval, $lval, -$hval, 'DF');
$j++;
}
//Legend
$this->SetXY($xval, $yval + $margin);
$this->Cell($lval, 5, $this->legends[$i],0,0,'C');
$i++;
}
//Scales
for ($i = 0; $i <= $nbDiv; $i++)
{
$ypos = $YDiag + $hRepere * $i;
$this->Line($XDiag, $ypos, $XDiag + $lDiag, $ypos);
$val = ($nbDiv - $i) * $valIndRepere;
$ypos = $YDiag + $hRepere * $i;
$xpos = $XDiag - $margin - $this->GetStringWidth($val);
$this->Text($xpos, $ypos, $val);
}
}
function SetLegends($data, $format)
{
$this->legends=array();
$this->wLegend=0;
$this->NbVal=count($data);
}
}
$pdf = new PDF_Diag();
$pdf->AddPage();
$data[0] = array(470, 490, 90);
$data[1] = array(450, 530, 110);
$data[2] = array(420, 580, 100);
// Column chart
$pdf->SetFont('Arial', 'BIU', 12);
$pdf->Cell(210, 5, 'Chart Title', 0, 1, 'C');
$pdf->Ln(8);
$valX = $pdf->GetX();
$valY = $pdf->GetY();
$pdf->ColumnChart(110, 100, $data, null, array(255,175,100));
//$pdf->SetXY($valX, $valY);
$pdf->Output();
?>
Trying to add a transparent PNG watermark to jpg images get's me different results either if i'm on localhost or production server.
Here's the results...
On my localhost (PHP Version 5.6.24)
On production server (PHP Version 5.5.9-1ubuntu4.21)
I don't even know what to call this problem of the blue color turning pink and the logo doesn't get correctly rendered...
The code is this:
function getBrightness($gdHandle) {
$width = imagesx($gdHandle);
$height = imagesy($gdHandle);
$totalBrightness = 0;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($gdHandle, $x, $y);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$totalBrightness += (max($red, $green, $blue) + min($red, $green, $blue)) / 2;
}
}
// imagedestroy($gdHandle);
return ($totalBrightness / ($width * $height)) / 2.55;
}
function render_text_on_gd_image(&$source_gd_image, $text, $font, $size, $color, $opacity, $rotation, $bpx, $bpy, $wnewx) {
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$bb = imagettfbbox($size, $rotation, $font, $text);
$x0 = min($bb[0], $bb[2], $bb[4], $bb[6]);
$x1 = max($bb[0], $bb[2], $bb[4], $bb[6]);
$y0 = min($bb[1], $bb[3], $bb[5], $bb[7]);
$y1 = max($bb[1], $bb[3], $bb[5], $bb[7]);
$bb_width = abs($x1 - $x0);
$bb_height = abs($y1 - $y0);
$alpha_color = imagecolorallocatealpha(
$source_gd_image,
hexdec(substr($color, 0, 2)),
hexdec(substr($color, 2, 2)),
hexdec(substr($color, 4, 2)),
127 * (100 - $opacity) / 100
);
return imagettftext($source_gd_image, $size, $rotation, $bpx + $wnewx/2 - $bb_width/2 , $bpy, $alpha_color, $font, $text);
}
$val = array();
//$val["displayName"] = "Administrador";
$val["displayName"] = "Afonso Ferreira Gomes";
$val["relFile"] = "imagem.jpg";
list($val["width_original"], $val["height_original"]) = getimagesize($val["relFile"]);
if ($val["width_original"] > $val["height_original"] && $val["width_original"] >= 1200) {
$val["height_resized"] = $val["height_original"] * (1200/$val["width_original"]);
$val["width_resized"] = 1200;
} elseif ($val["height_original"] > $val["width_original"] && $val["height_original"] >= 1200) {
$val["height_resized"] = 1200;
$val["width_resized"] = (1200/$val["height_original"]) * $val["width_original"];
} else {
$val["height_resized"] = $val["height_original"];
$val["width_resized"] = $val["width_original"];
}
$i = imagecreatefromjpeg($val["relFile"]);
$i = imagescale($i, $val["width_resized"], $val["height_resized"]);
$val["width_new"] = imagesx($i);
$val["height_new"] = imagesy($i);
if ($val["width_new"] < $val["height_new"]) {
$val["portait"] = true;
$val["smallest"] = $val["width_new"];
} else {
$val["portait"] = false;
$val["smallest"] = $val["height_new"];
}
/* GERAR WATERMARK LOGOTIPO */
$val["racio"] = 0.20;
$val["marLeft"] = 40;
$val["marBottom"] = 40;
$val["bright"] = getBrightness($i);
if ($val["bright"] < 30) {
$val["opacidade"] = 20;
} else {
$val["opacidade"] = 40;
}
$w = imagecreatefrompng("jbw_260_40.png");
if ($val["portait"]) {
$val["water_width"] = $val["width_new"] * $val["racio"];
$val["water_height"] = $val["width_new"] * $val["racio"];
} else {
$val["water_width"] = $val["height_new"] * $val["racio"];
$val["water_height"] = $val["height_new"] * $val["racio"];
}
$wnew = imagescale($w, $val["water_width"], $val["water_height"]);
$val["water_width"] = imagesx($wnew);
$val["water_height"] = imagesy($wnew);
/* GERAR WATERMARK TEXTO AUTOR */
if ($val["displayName"] == "Administrador") {
$val["autor"] = "";
$val["marBottom"] = 20;
$val["marLeft"] = 20;
} else {
$val["autor"] = $val["displayName"];
}
// PRIMEIRO E ULTIMO NOME SÓ!!
$autorNomes = explode(" ", $val["autor"]);
if (count($autorNomes) >= 2) {
$val["autor"] = $autorNomes[0] . " " . $autorNomes[count($autorNomes) - 1];
} else {
$val["autor"] = $autorNomes[0];
}
$font = "../font/Montserrat.ttf";
$color = "FFFFFF";
$flagSize = false;
$val["fontSize"] = 12;
for ($size = 7; $size <= 50; $size += 0.5) {
$bb = imagettfbbox($size, 0, $font, $val["autor"]);
$x0 = min($bb[0], $bb[2], $bb[4], $bb[6]);
$x1 = max($bb[0], $bb[2], $bb[4], $bb[6]);
$y0 = min($bb[1], $bb[3], $bb[5], $bb[7]);
$y1 = max($bb[1], $bb[3], $bb[5], $bb[7]);
$val["bbox_width"] = abs($x1 - $x0);
$val["bbox_height"] = abs($y1 - $y0);
if (($val["bbox_width"] >= $val["water_width"] && !$flagSize) || $size == 50) {
$val["fontSize"] = $size;
$flagSize = true;
break;
}
}
$val["posY_water"] = $val["height_new"] - $val["water_height"] - $val["marBottom"];
$val["posY_text"] = $val["height_new"] - $val["marBottom"] + $val["bbox_height"] - 5;
imagecopy($i, $wnew, $val["marLeft"], $val["posY_water"] , 0, 0, $val["water_width"], $val["water_height"]);
render_text_on_gd_image($i, $val["autor"], $font, $val["fontSize"], $color, $val["opacidade"] ,0 , $val["marLeft"] , $val["posY_text"], $val["water_width"]);
// echo "<pre>"; print_r($val); echo "</pre>"; die;
/* OUTPUT IMAGEM E LIMPA BUFFER */
header('Content-type: image/png');
imagepng($i);
imagedestroy($i);
imagedestroy($w);
And this are the gd section of phpinfo for localhost and production server
What am I missing? this is driving me insane!
Those issues almost always object to the alpha channel of either the source or destination not beeing preserved or the output not really beeing true color.
Try using the imagesavealpha() function and search for "alpha" in the comments of the PHP documentation because there are many people having solutions to similiar issues.
This comment might be helpful and is kinda what Esko said:
http://php.net/manual/en/function.imagecreatefrompng.php#90364
Basically it copies an image to a buffer using imagecreatetruecolor().
I'm having the same issue. The imageScale function in Ubuntu seems to turn greens and blues to pink. Solution could be to use imagecopyresampled and imagecreatetruecolor. However this solution is way slower.
I am using ImageMagic for a project, Since i use windows i installed wamp, i want to convert some text into images, insert effects and make an animated gif out of it, i tried various folder options finally ended up with this, which does not work as well. Can someone help? the code which i am using right now is "D:\Program Files\EasyPHP\data\localweb\imgmgk\convert" -background "" -fill "#000" -font Arial -pointsize 12 label:" hi casino" "D:\Program Files\EasyPHP\data\localweb\files\bum.jpg" a link to ImageMagick http://www.imagemagick.org/script/convert.php
Try Imagick,
Imagick is a native php extension to create and modify images using the ImageMagick API.
ImageMagick is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.
By using this, we have an example.
whirlyGif
function lerp($t, $a, $b)
{
return $a + ($t * ($b - $a));
}
class Dot
{
public function __construct($color, $sequence, $numberDots, $imageWidth, $imageHeight)
{
$this->color = $color;
$this->sequence = $sequence;
$this->numberDots = $numberDots;
$this->imageWidth = $imageWidth;
$this->imageHeight = $imageHeight;
if ($this->numberDots < 0) {
$this->numberDots = 0;
}
}
public function calculateFraction($frame, $maxFrames, $timeOffset, $phaseMultiplier, $phaseDivider)
{
$frame = -$frame;
$totalAngle = 2 * $phaseMultiplier;
$fraction = ($frame / $maxFrames * 2);
$fraction += $totalAngle * ($this->sequence / $this->numberDots);
if ($phaseDivider != 0) {
$fraction += (($this->sequence)) / ($phaseDivider);
}
$fraction += $timeOffset;
while ($fraction < 0) {
//fmod does not work 'correctly' on negative numbers
$fraction += 64;
}
$fraction = fmod($fraction, 2);
if ($fraction > 1) {
$unitFraction = 2 - $fraction;
}
else {
$unitFraction = $fraction;
}
return $unitFraction * $unitFraction * (3 - 2 * $unitFraction);
}
public function render(\ImagickDraw $draw, $frame, $maxFrames, $phaseMultiplier, $phaseDivider)
{
$innerDistance = 40;
$outerDistance = 230;
$sequenceFraction = $this->sequence / $this->numberDots;
$angle = 2 * M_PI * $sequenceFraction;
$trailSteps = 5;
$trailLength = 0.1;
$offsets = [
100 => 0,
];
for ($i=0; $i<=$trailSteps; $i++) {
$key = intval(50 * $i / $trailSteps);
$offsets[$key] = $trailLength * ($trailSteps - $i) / $trailSteps;
}
//TODO - using a pattern would make the circles look more natural
//$draw->setFillPatternURL();
foreach ($offsets as $alpha => $offset) {
$distanceFraction = $this->calculateFraction($frame, $maxFrames, $offset, $phaseMultiplier, $phaseDivider);
$distance = lerp($distanceFraction, $innerDistance, $outerDistance);
$xOffset = $distance * sin($angle);
$yOffset = $distance * cos($angle);
$draw->setFillColor($this->color);
$draw->setFillAlpha($alpha / 100);
$xOffset = $xOffset * $this->imageWidth / 500;
$yOffset = $yOffset * $this->imageHeight / 500;
$xSize = 4 * $this->imageWidth / 500;
$ySize = 4 * $this->imageHeight / 500;
$draw->circle(
$xOffset,
$yOffset,
$xOffset + $xSize,
$yOffset + $ySize
);
}
}
}
function whirlyGif($numberDots, $numberFrames, $loopTime, $backgroundColor, $phaseMultiplier, $phaseDivider)
{
$aniGif = new \Imagick();
$aniGif->setFormat("gif");
$width = 500;
$height = $width;
$numberDots = intval($numberDots);
if ($numberDots < 1) {
$numberDots = 1;
}
$maxFrames = $numberFrames;
$frameDelay = ceil($loopTime / $maxFrames);
$scale = 1;
$startColor = new \ImagickPixel('red');
$dots = [];
for ($i=0; $i<$numberDots; $i++) {
$colorInfo = $startColor->getHSL();
//Rotate the hue by 180 degrees
$newHue = $colorInfo['hue'] + ($i / $numberDots);
if ($newHue > 1) {
$newHue = $newHue - 1;
}
//Set the ImagickPixel to the new color
$color = new \ImagickPixel('#ffffff');
$colorInfo['saturation'] *= 0.95;
$color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']);
$dots[] = new Dot($color, $i, $numberDots, $width, $height);
}
for ($frame = 0; $frame < $maxFrames; $frame++) {
$draw = new \ImagickDraw();
$draw->setStrokeColor('none');
$draw->setFillColor('none');
$draw->rectangle(0, 0, $width, $height);
$draw->translate($width / 2, $height / 2);
foreach ($dots as $dot) {
/** #var $dot Dot */
$dot->render($draw, $frame, $maxFrames, $phaseMultiplier, $phaseDivider);
}
//Create an image object which the draw commands can be rendered into
$imagick = new \Imagick();
$imagick->newImage($width * $scale, $height * $scale, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->setImageDispose(\Imagick::DISPOSE_PREVIOUS);
//Render the draw commands in the ImagickDraw object
//into the image.
$imagick->drawImage($draw);
$imagick->setImageDelay($frameDelay);
$aniGif->addImage($imagick);
$imagick->destroy();
}
$aniGif->setImageFormat('gif');
$aniGif->setImageIterations(0); //loop forever
$aniGif->mergeImageLayers(\Imagick::LAYERMETHOD_OPTIMIZEPLUS);
header("Content-Type: image/gif");
echo $aniGif->getImagesBlob();
}
The output will be
You can find more examples here
Sorted! Thanks a lot for helping me out.
There was one file which i could not get from the tutorial url, here is the alternate link.
http://windows.php.net/downloads/pecl/releases/imagick/3.1.2/php_imagick-3.1.2-5.5-ts-vc11-x86.zip
I've tried experimenting with the GD library to simulate Photoshop's muliply effect, but I haven't found a working solution yet.
According to Wikipedia, the multiply blend mode:
[...] multiplies the numbers for each pixel of the top layer with the corresponding pixel for the bottom layer. The result is a darker picture.
Does anyone know of a way to achieve this using PHP? Any help would be much appreciated.
You need to take every pixel of your image, then multiply each RGB value with your background color / 255 (it's the Photoshop formula). For example, a JPG file with a red background color multiply filter, saved as a PNG file for better results:
<?php
$filter_r=216;
$filter_g=0;
$filter_b=26;
$suffixe="_red";
$path=YOURPATHFILE;
if(is_file($path)){
$image=#imagecreatefromjpeg($path);
$new_path=substr($path,0,strlen($path)-4).$suffixe.".png";
$imagex = imagesx($image);
$imagey = imagesy($image);
for ($x = 0; $x <$imagex; ++$x) {
for ($y = 0; $y <$imagey; ++$y) {
$rgb = imagecolorat($image, $x, $y);
$TabColors=imagecolorsforindex ( $image , $rgb );
$color_r=floor($TabColors['red']*$filter_r/255);
$color_g=floor($TabColors['green']*$filter_g/255);
$color_b=floor($TabColors['blue']*$filter_b/255);
$newcol = imagecolorallocate($image, $color_r,$color_g,$color_b);
imagesetpixel($image, $x, $y, $newcol);
}
}
imagepng($image,$new_path);
}
?>
I've been looking for Multiply blend between two images as well and couldn't find any native-php solution for it. It appears that only way (for now) is to "manually" set pixels, pixel-by-pixel. Here's my code that does Multiply blend between two images, assuming that images are of the same size. You can adjust it to handle different sizes if you like.
function multiplyImage($dst,$src)
{
$ow = imagesx($dst);
$oh = imagesy($dst);
$inv255 = 1.0/255.0;
$c = imagecreatetruecolor($ow,$oh);
for ($x = 0; $x <$ow; ++$x)
{
for ($y = 0; $y <$oh; ++$y)
{
$rgb_src = imagecolorsforindex($src,imagecolorat($src, $x, $y));
$rgb_dst = imagecolorsforindex($dst,imagecolorat($dst, $x, $y));
$r = $rgb_src['red'] * $rgb_dst['red']*$inv255;
$g = $rgb_src['green'] * $rgb_dst['green']*$inv255;
$b = $rgb_src['blue'] * $rgb_dst['blue']*$inv255;
$rgb = imagecolorallocate($c,$r,$g,$b);
imagesetpixel($c, $x, $y, $rgb);
}
}
return $c;
}
Function returns image object so you should ensure to do imagedestroy after you're done using it.
There should be a workaround using overlay native-php blend, which suggests that 50% gray pixels of destination image will be affected by source pixels. In theory, if you do need to blend two black-and-white images (no gray tones), if you set contrast of destination image so white will become 50%-gray, and then overlay-blend source image over it, should give you something similar to multiply. But for color images, or grayscale images, this wouldn't work - above method appears to be the only option.
I was led into this thread when I needed to blend two images in GD. It seems there is no code specifically for that so I will just leave this here for future visitors to this page.
This is a fork from the answer of colivier that supports multiply-blending of two images.
The two images need not be of the same size BUT the overlaying image will be resized and cropped to the size of the bottom layer. I made a fit helper function to do just that but don't bother with that.
imagecolorat returns the base color, even with PNGs with transparency. That is, a 50% black (visible as (128, 128, 128)) will be returned as (0, 0, 0, 64) 64 being the alpha value. This code takes into consideration translucency and converts the translucent colors to the visible color values.
// bottom layer
$img1 = imagecreatefromjpeg(realpath(__DIR__.'/profilePic.jpg'));
// top layer
$img2 = imagecreatefrompng(realpath(__DIR__.'/border2.png'));
imagealphablending($img2, false);
imagesavealpha($img2, true);
$imagex = imagesx($img1);
$imagey = imagesy($img1);
$imagex2 = imagesx($img2);
$imagey2 = imagesy($img2);
// Prereq: Resize img2 to match img1, cropping beyond the aspect ratio
$w1 = max(min($imagex2, $imagex), $imagex);
$h1 = max(min($imagey2, $imagey), $imagey);
$w_using_h1 = round($h1 * $imagex2 / $imagey2);
$h_using_w1 = round($w1 * $imagey2 / $imagex2);
if ($w_using_h1 > $imagex) {
fit($img2, $imagex, $imagey, 'HEIGHT', true);
}
fit($img2, $imagex, $imagey, 'WIDTH', true);
// Actual multiply filter
for ($x = 0; $x < $imagex; ++$x) {
for ($y = 0; $y < $imagey; ++$y) {
$rgb1 = imagecolorat($img1, $x, $y);
$rgb2 = imagecolorat($img2, $x, $y);
$idx1 = imagecolorsforindex($img1, $rgb1);
$idx2 = imagecolorsforindex($img2, $rgb2);
// Shift left 8, then shift right 7
// same as multiply by 256 then divide by 128
// approximate multiply by 255 then divide by 127
// This is basically multiply by 2 but, expanded to show that
// we are adding a fraction of white to the translucent image
// $adder = ($idx2['alpha'] << 8 >> 7);
$adder = ($idx2['alpha'] << 1);
$rmul = min(255, $idx2['red'] + $adder);
$gmul = min(255, $idx2['green'] + $adder);
$bmul = min(255, $idx2['blue'] + $adder);
$color_r = floor($idx1['red'] * $rmul / 255);
$color_g = floor($idx1['green'] * $gmul / 255);
$color_b = floor($idx1['blue'] * $bmul / 255);
$newcol = imagecolorallocatealpha($img1, $color_r, $color_g, $color_b, 0);
imagesetpixel($img1, $x, $y, $newcol);
}
}
imagejpeg($img1, __DIR__.'/out.jpg');
/**
* Fits an image to a $w x $h canvas
*
* #param type $w Target width
* #param type $h Target height
* #param int $fit_which Which dimension to fit
* #param bool $upscale If set to true, will scale a smaller image to fit the given dimensions
* #param bool $padded If set to true, will add padding to achieve given dimensions
*
* #return Image object
*/
function fit(&$img, $w, $h, $fit_which = 'BOTH', $upscale = false, $padded = true) {
if (!in_array($fit_which, array('WIDTH', 'HEIGHT', 'BOTH'))) {
$fit_which = 'BOTH';
}
$w0 = imagesx($img);
$h0 = imagesy($img);
if (!$upscale && $w0 <= $w && $h0 <= $h)
return $this;
if ($padded) {
$w1 = max(min($w0, $w), $w);
$h1 = max(min($h0, $h), $h);
}
else {
$w1 = min($w0, $w);
$h1 = min($h0, $h);
}
$w_using_h1 = round($h1 * $w0 / $h0);
$h_using_w1 = round($w1 * $h0 / $w0);
// Assume width, crop height
if ($fit_which == 'WIDTH') {
$w2 = $w1;
$h2 = $h_using_w1;
}
// Assume height, crop width
elseif ($fit_which == 'HEIGHT') {
$w2 = $w_using_h1;
$h2 = $h1;
}
elseif ($fit_which == 'BOTH') {
if (!$padded) {
$w2 = $w = min($w, $w_using_h1);
$h2 = $h = min($h, $h_using_w1);
}
else {
// Extend vertically
if ($h_using_w1 <= $h) {
$w2 = $w1;
$h2 = $h_using_w1;
}
// Extend horizontally
else {
$w2 = $w_using_h1;
$h2 = $h1;
}
}
}
$im2 = imagecreatetruecolor($w, $h);
imagealphablending($im2, true);
imagesavealpha($im2, true);
$transparent = imagecolorallocatealpha($im2, 255, 255, 255, 127);
imagefill($im2, 0, 0, $transparent);
imagealphablending($img, true);
imagesavealpha($img, true);
// imagefill($im, 0, 0, $transparent);
imagecopyresampled($im2, $img, ($w - $w2) / 2, ($h - $h2) / 2, 0, 0, $w2, $h2, $w0, $h0);
$img = $im2;
}
Have you tried to use php manual?
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.
<?php
function multiplyColor(&$im, $color = array(255, 0, 0)) {
//get opposite color
$opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);
//now we subtract the opposite color from the image
imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
If used with png image and alpha must be well and works very well
$filter_r=215;
$filter_g=5;
$filter_b=5;
$alpha=70;
$suffixe="_red";
$path="./img/foto_220_590.png";
if(is_file($path)){
$image=imagecreatefrompng($path);
$new_path=substr($path,0,strlen($path)-4).$suffixe.".png";
echo $imagex = imagesx($image);
echo $imagey = imagesy($image);
for ($x = 0; $x <$imagex; ++$x) {
for ($y = 0; $y <$imagey; ++$y) {
$rgb = imagecolorat($image, $x, $y);
$TabColors=imagecolorsforindex ( $image , $rgb );
$color_r=floor($TabColors['red']*$filter_r/255);
$color_g=floor($TabColors['green']*$filter_g/255);
$color_b=floor($TabColors['blue']*$filter_b/255);
//$newcol = imagecolorallocate($image, $color_r,$color_g,$color_b);
// this new alpha
$newcol = imagecolorallocatealpha($image, $color_r,$color_g,$color_b,$alpha);
imagesetpixel($image, $x, $y, $newcol);
}
}
imagepng($image,$new_path);
I updated #colivier script to be able to myltiply two images, and not just an image with a color:
/**
* Multiply $pathToDst and $pathToSrc to $resultPath
*
* #param string $pathToDst
* #param string $pathToSrc
* #param string $resultPath
*/
function multiply($pathToDst, $pathToSrc, $resultPath) {
switch (pathinfo($pathToDst, PATHINFO_EXTENSION)) {
case "gif" :
$resourceDst = imagecreatefromgif($pathToDst);
break;
case "png" :
$resourceDst = imagecreatefrompng($pathToDst);
break;
default :
$resourceDst = imagecreatefromjpeg($pathToDst);
break;
}
switch (pathinfo($pathToSrc, PATHINFO_EXTENSION)) {
case "gif" :
$resourceSrc = imagecreatefromgif($pathToSrc);
break;
case "png" :
$resourceSrc = imagecreatefrompng($pathToSrc);
break;
default :
$resourceSrc = imagecreatefromjpeg($pathToSrc);
break;
}
for ($x = 0; $x < 400; ++$x) {
for ($y = 0; $y < 400; ++$y) {
$TabColorsFlag = imagecolorsforindex($resourceDst, imagecolorat($resourceDst, $x, $y));
$TabColorsPerso = imagecolorsforindex($resourceSrc, imagecolorat($resourceSrc, $x, $y));
$color_r = floor($TabColorsFlag['red'] * $TabColorsPerso['red'] / 255);
$color_g = floor($TabColorsFlag['green'] * $TabColorsPerso['green'] / 255);
$color_b = floor($TabColorsFlag['blue'] * $TabColorsPerso['blue'] / 255);
imagesetpixel($resourceDst, $x, $y, imagecolorallocate($resourceSrc, $color_r, $color_g, $color_b));
}
}
imagepng($resourceDst, $resultPath, 0);
imagedestroy($resourceDst);
imagedestroy($resourceSrc);
}
i have following captcha code:
<?php
class CaptchaView extends View
{
private $fontsDir = 'captcha_resources/fonts/';
private $backgroundsDir = 'captcha_resources/backgrounds/';
private static $dirCache = array();
public function render($controller)
{
$code = $controller->viewVars["code"];
/**
* The next part is orginnaly written by ted from mastercode.nl and modified for using in this mod.
**/
header("content-type:image/png");
header('Cache-control: no-cache, no-store');
$width = 100;
$height = 30;
$img = imagecreatefrompng(self::backgroundImage());
// add noise
for ($i = 0; $i < 1; $i++) {
$horizontal_progress = 0;
$vertical_pos = rand(1, $height / 2);
do {
$horizontal_step_size = floor(rand(1, $width / 5));
imageline($img, $horizontal_progress, $vertical_pos, ($horizontal_progress += $horizontal_step_size), ($vertical_pos = rand(1, $height)), self::color("tekst"));
} while ($horizontal_progress < $width);
}
$background = imagecolorallocate($img, self::color("bg"), self::color("bg"), self::color("bg"));
for ($g = 0; $g < 30; $g++) {
$t = rand(10, 20);
$t = $t[0];
$ypos = rand(0, $height);
$xpos = rand(0, $width);
$kleur = imagecolorallocate($img, self::color("bgtekst"), self::color("bgtekst"), self::color("bgtekst"));
imagettftext($img, self::size(), self::move(), $xpos, $ypos, $kleur, self::font(), $t);
}
$stukje = $width / (strlen($code) + 3) + 5;
for ($j = 0; $j < strlen($code); $j++) {
$tek = $code[$j];
$ypos = rand(23, 27);
$xpos = $stukje * ($j + 1) - 5;
$color2 = imagecolorallocate($img, self::color("tekst"), self::color("tekst"), self::color("tekst"));
imagettftext($img, self::size(), self::move(), $xpos, $ypos, $color2, self::font(), $tek);
}
imagepng($img);
imagedestroy($img);
}
/**
* Some functions :)
* Also orginally written by mastercode.nl
**/
/**
* Function to create a random color
* #auteur mastercode.nl
* #param $type string Mode for the color
* #return int
**/
private static function color($type)
{
switch ($type) {
case "bg":
$color = rand(224, 255);
break;
case "tekst":
$color = rand(0, 127);
break;
case "bgtekst":
$color = rand(200, 224);
break;
default:
$color = rand(0, 255);
break;
}
return $color;
}
/**
* Function to ranom the size
* #auteur mastercode.nl
* #return int
**/
private static function size()
{
return rand(18, 22);
}
/**
* Function to random the posistion
* #auteur mastercode.nl
* #return int
**/
private static function move()
{
return rand(-22, 22);
}
/**
* Function to return a ttf file from fonts map
* #auteur mastercode.nl
* #return string
**/
function randomFileByExt($dir, $ext)
{
$f = opendir($dir);
if (empty(self::$dirCache[$dir])) {
$ar = array();
while (($file = #readdir($f)) !== false) {
if (!in_array($file, array('.', '..')) && substr_compare($file, $ext, -strlen($ext)) == 0) {
$ar[] = $file;
}
}
self::$dirCache[$dir] = $ar;
} else {
$ar = self::$dirCache[$dir];
}
if (count($ar)) {
$i = rand(0, (count($ar) - 1));
return $dir . $ar[$i];
}
}
private function backgroundImage()
{
return self::randomFileByExt(Config::get("VIEWS_PATH") . $this->backgroundsDir, ".png");
}
private function font()
{
return self::randomFileByExt(Config::get("VIEWS_PATH") . $this->fontsDir, ".ttf");
}
}
actually it display 4 letters with a disturbed background
i want block some spam bot them i think to modify code to increase security increasing number of letters
can you tell me how to modify it to display 6 letters instead of 4?
1) Best solution is to implement existing Captcha like reCaptcha or so..
docs : http://code.google.com/intl/en_EN/apis/recaptcha/intro.html
PHP : http://code.google.com/intl/en_EN/apis/recaptcha/docs/php.html
2) To modify your code to push 6 instead of 4 letters edit part of code like this:
$stukje = $width / (strlen($code) + 5) + 5; //instead of "+3) +5;"
should do the trick, but I can't test it, since I don't know in which mod it was used (what CMS, PHP Framework,...)