I'm in need of drawing continuous lines in PHP. GD apparently can't do it, but imagick has a polyline function. Now my test code:
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('white'));
$draw = new ImagickDraw();
$draw->setStrokeWidth(3);
$line = array(
array('x'=>10, 'y'=>10),
array('x'=>50, 'y'=>10),
array('x'=>70, 'y'=>40),
array('x'=>30, 'y'=>60),
);
$draw->polyline($line);
$image->drawImage($draw);
$image->setImageFormat('jpg');
$image->writeImage("test.jpg");
produces a CLOSED (and filled) polygon for reasons I can't fathom. What's going on here and how do I fix it? I want it to stop at the last point and NOT close or fill.
If there's a solution in GD, I'm also happy. No, I can't simply string individual lines together, because I want thickness in the lines.
It is possible to draw an open polyline by drawing in one direction and then back with the same points table, without first and last point (they are not neccessary)
so, if you have
$line = array(
array('x'=>10, 'y'=>10),
array('x'=>50, 'y'=>10),
array('x'=>70, 'y'=>40),
array('x'=>30, 'y'=>60),
);
you should add
$line[] = array('x'=>70, 'y'=>40);
$line[] = array('x'=>50, 'y'=>10);
and then
$draw->polyline($line);
and you would get what you want.
Looks at the documentation of GD polyline. Perhaps it that you want : http://bonzoli.com/sourcecode/index.php/man/GD::Polyline
You should define both the stroke and fill colors, otherwise Imagick will "fill" the area bounded by the line and the start and finish points with the fill color. The defaults are for these values are "white" and "black".
This code will work as intended, i.e. it produces a mirrored "c" shaped object with black lines of 3 pixels width:
$image = new Imagick();
$image->newImage(100, 100, 'white');
$draw = new ImagickDraw();
$draw->setStrokeWidth(3);
$draw->setStrokeColor ("black");
$draw->setFillColor ("none");
$line = array(
array('x'=>10, 'y'=>10),
array('x'=>50, 'y'=>10),
array('x'=>70, 'y'=>40),
array('x'=>30, 'y'=>60),
);
$draw->polyline($line);
$image->drawImage($draw);
$image->writeImage("test.jpg");
Related
I'm adding some heading in Russian on the image using newPseudoImage and CAPTION.
Heading can have some entities like — etc, so I clean it with html_entity_decode.
In some cases it works well, but in some cases text after decoded entity goes in wrong encoding, like that:
look at second line - there is the problem
Please, help me to find the solution.
If I use annotateImage - everything is nice.
If I use newPseudoImage and LABEL - everything is nice.
The problem appears only with newPseudoImage and CAPTION (but I have to CAPTION, cause I need to scale my headings depending on their length).
At the same time I have to use these entities in headings (i.e. to avoid wrapping of the dash to the next line).
Some headings shows nice:
'Путешествие в Карелию' - is fine, but 'Нуорунен в Карелии' - shows with error.
My code:
$postTitle = 'Нуорунен в Карелии';
$postTitle = html_entity_decode($postTitle);
$mainImage = new Imagick('source.jpg');
$title = new Imagick();
$colorize = new Imagick();
$mainImage->setImageCompressionQuality(85);
$title->setBackgroundColor('transparent');
$title->setFont('/fonts/roboto-slab_semibold.ttf');
$title->setGravity(imagick::GRAVITY_CENTER);
$title->newPseudoImage( 780, 480, "CAPTION:" . $postTitle );
$colorize->newImage(1, 1, new ImagickPixel('#f8bb00'));
$title->clutImage($colorize);
$colorize->destroy();
$mainImage->compositeImage($title, imagick::COMPOSITE_DEFAULT, 210, 110);
$mainImage->writeImage('image.jpg');
I'm learning and practicing my Imagick skills.
I have issues with outlined text using Imagick stroke. I would like to achieve an effect visible on this image: a popular Internet meme:
Here's the code I have so far:
$draw = new \ImagickDraw();
$outputImage = new \Imagick('meme.jpg');
$draw->setFillColor('#fff');
$draw->setFont('impact.ttf');
$draw->setFontSize(40);
$draw->setGravity(\Imagick::GRAVITY_NORTH);
$draw->setStrokeColor('#000');
$draw->setStrokeWidth(1);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
$outputImage->annotateImage($draw, 0, 5, 0, 'Sample text');
$outputImage->setFormat('png');
$outputImage->writeimage('tmp/meme.png');
The issue: text stroke does not look nice. I've found a tip on Imagick discussion board about annotating image second time, but without stroke. Does not work.
Before writing image:
$draw->setStrokeColor('transparent');
$outputImage->annotateImage($draw, 0, 5, 0, 'Sample text');
Can anybody give me a clue?
Update
To conclude, my generated image looks as following:
As you can see, I have some issues with 2px stroke while using different font size. On big fonts, it looks nice but with smaller font there are some issues with the stroke and font.
Version1: resizing
Version 2: composite over and resizing
Version 2 gives a much better result. See code below. Depending on the final size, you need to play around with font and stroke size, as the resizing may give unwanted effects. You may also try version 2 without resizing.
Version 1: resizing
$draw = new ImagickDraw();
$draw->setFillColor('#fff');
$draw->setFont('impact.ttf');
$draw->setFontSize(100); //use a large font-size
$draw->setStrokeColor('#000');
$draw->setStrokeWidth(4);
$draw->setStrokeAntialias(true); //try with and without
$draw->setTextAntialias(true); //try with and without
$outputImage = new Imagick();
$outputImage->newImage(1400,400, "transparent"); //transparent canvas
$outputImage->annotateImage($draw, 20, 100, 0, 'STOP ME FROM MEMEING');
$outputImage->trimImage(0); //Cut off transparent border
$outputImage->resizeImage(300,0, imagick::FILTER_CATROM, 0.9, false); //resize to final size
/*
Now you can compositve over the image
*/
//Clean up
$draw->clear();
$draw->destroy();
$outputImage->clear();
$outputImage->destroy();
Version 2: composite over and resizing
$draw = new ImagickDraw();
$draw->setFont('impact.ttf');
$draw->setFontSize(100); //use a large font-size
$draw->setStrokeAntialias(true); //try with and without
$draw->setTextAntialias(true); //try with and without
//Create text
$draw->setFillColor('#fff');
$textOnly = new Imagick();
$textOnly->newImage(1400,400, "transparent"); /transparent canvas
$textOnly->annotateImage($draw, 21, 101, 0, 'STOP ME FROM MEMEING'); //parameters depend of stroke and text size
//Create stroke
$draw->setFillColor('#000'); //same as stroke color
$draw->setStrokeColor('#000');
$draw->setStrokeWidth(8);
$strokeImage = new Imagick();
$strokeImage->newImage(1400,400, "transparent");
$strokeImage->annotateImage($draw, 20, 100, 0, 'STOP ME FROM MEMEING');
//Composite text over stroke
$strokeImage->compositeImage($textOnly, imagick::COMPOSITE_OVER, 0, 0, Imagick::CHANNEL_ALPHA );
$strokeImage->trimImage(0); //cut transparent border
$strokeImage->resizeImage(300,0, imagick::FILTER_CATROM, 0.9, false); //resize to final size
/*
Now you can compositve over the image
*/
//Clean up
$draw->clear();
$draw->destroy();
$strokeImage->clear();
$strokeImage->destroy();
$textOnly->clear();
$textOnly->destroy();
Can you post your result or be more specific what doesn't look fine to you?
A solution could be to create the text (with stroke) first on a transaprent background and then composite it over the image. You could create the text in bigger font size and resize to make it look smoother on the final image.
Trying to take a rectangular photo, crop it into a square region, and then mask it into a circular with a transparent background.
//$dims is an array with the width, height, x, y of the region in the rectangular image (whose path on disk is $tempfile)
$circle = new \Imagick();
$circle->newImage($dims['w'], $dims['h'], 'none');
$circle->setimageformat('png');
$circle->setimagematte(true);
$draw = new \ImagickDraw();
$draw->setfillcolor('#ffffff');
$draw->circle($dims['w']/2, $dims['h']/2, $dims['w']/2, $dims['w']);
$circle->drawimage($draw);
$imagick = new \Imagick();
$imagick->readImage($tempfile);
$imagick->setImageFormat( "png" );
$imagick->setimagematte(true);
$imagick->cropimage($dims['w'], $dims['h'], $dims['x'], $dims['y']);
$imagick->compositeimage($circle, \Imagick::COMPOSITE_DSTIN, 0, 0);
$imagick->writeImage($tempfile);
$imagick->destroy();
The result is the rectangular image, uncropped and without being circularized. What am I doing wrong?
Example image:
Example input for $dims = {"x":253,"y":0,"x2":438.5,"y2":185.5,"w":185.5,"h":185.5}
Rough expected output:
Image i'm getting looks roughly like the input image.
For those with an older version of Imagick (setimagematte does not exist in version lower than 6.2.9), I came up with an easy solution. The thing here is to copy opacity from the mask to the original image.
Original Image:
Mask:
Result:
The code:
$base = new Imagick('original.jpg');
$mask = new Imagick('mask.png');
$base->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
$base->writeImage('result.png');
You could use an Imagick black circle as mask but I though it wasn't perfect so I used my own.
Of course you will certainly have to resize / crop your images but that's another story.
Hope this helps.
J.
This works for me:
<?php
//$dims is an array with the width, height, x, y of the region in the rectangular image (whose path on disk is $tempfile)
$tempfile = 'VDSlU.jpg';
$outfile = 'blah.png';
$circle = new Imagick();
$circle->newImage(185.5, 185.5, 'none');
$circle->setimageformat('png');
$circle->setimagematte(true);
$draw = new ImagickDraw();
$draw->setfillcolor('#ffffff');
$draw->circle(185.5/2, 185.5/2, 185.5/2, 185.5);
$circle->drawimage($draw);
$imagick = new Imagick();
$imagick->readImage($tempfile);
$imagick->setImageFormat( "png" );
$imagick->setimagematte(true);
$imagick->cropimage(185.5, 185.5, 253, 0);
$imagick->compositeimage($circle, Imagick::COMPOSITE_DSTIN, 0, 0);
$imagick->writeImage($outfile);
$imagick->destroy();
?>
<img src="blah.png">
I always try to keep the code simple until I get it working and then add all the variables etc. That could be the problem or there could be a problem with your version of Imagick.
It's namespaced
Still do not know what it means! - I am getting a bit behind with php as I do not use it very much these days.
There's also another workaround that I suggest here :
// create an imagick object of your image
$image = new \Imagick('/absolute/path/to/your/image');
// crop square your image from its center (100px witdh/height in my example)
$image->cropThumbnailImage(100, 100);
// then round the corners (0.5x the width and height)
$image->roundCorners(50, 50);
// force the png format for transparency
$image->setImageFormat("png");
// write the new image
$image->writeImage('/absolute/path/to/your/new/image');
// done!
Many thanks to all previous answers and contributors that lead me to this code!
Feel free to test/comment my solution!
I stumbled upon this as I was searching for a similar solution for Ruby on Rails, notice that this Stackoverflow question uses vignette instead which seems to be a much simpler way to solve the problem.
I used vignette to solve my problem with rounded images in Ruby on Rails using Dragonfly.
I want to make an area transparent within an Imagick object with a specific width, height and a top position.
For example I need a transparent area with 30px x 30px from the 15th px to the top but I can't find a way to do it.
$canvas1 = new Imagick();
$canvas1->newImage(30,60,'black','png');
Please help.
This may be a slightly simpler way of doing it. I recycled #AndreKR's setup code to get started:
$im = new Imagick();
$im->newImage(100,100, 'red');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE); // make sure it has an alpha channel
$box=$im->getImageRegion(30,30,15,15);
$box->setImageAlphaChannel(Imagick::ALPHACHANNEL_TRANSPARENT);
$im->compositeImage($box,Imagick::COMPOSITE_REPLACE,15,15);
While you can flood fill with transparency ink (not transparent ink) like this:
$im->floodFillPaintImage('#FF000000', 10, '#FFFFFF', 0, 0, false);
in this post, Anthony, apparently some important figure in the ImageMagick universe, says that you cannot draw with transparency.
So it seems you have to create a punch image and then use it to punch the transparent areas out in your actual image. To create the punch here I draw the rectangle opaque on a transparent brackground and then invert the whole image:
$punch = new Imagick();
$punch->newImage(100,100, 'transparent');
$drawing = new ImagickDraw();
$drawing->setFillColor(new ImagickPixel('black'));
$drawing->rectangle(15, 15, 45, 45);
$punch->drawImage($drawing);
$punch->negateImage(true, Imagick::CHANNEL_ALPHA);
Here's the actual image before the punching:
$im = new Imagick();
$im->newImage(100,100, 'red');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE); // make sure it has
// an alpha channel
Now we can copy over the alpha channel from our punch image. For a reason unknown to me the obvious way does not work:
// Copy over the alpha channel from one image to the other
// this does NOT work, the $channel parameter seems to be useless:
// $im->compositeImage($punch, Imagick::COMPOSITE_SRC, 0, 0, Imagick::CHANNEL_ALPHA);
However, these both work:
// Copy over the alpha channel from one image to the other
// $im->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
// $im->compositeImage($punch, Imagick::COMPOSITE_DSTIN, 0, 0);
(The light blue is the background of the Windows photo viewer, indicating transparent areas.)
You can set the opacity as follows
$image->setImageOpacity(0.0);
If you set it to 0.0 the image what you have crated will become transparent
for more information you can Set opacity in Imagick
if you want it for a particular area part then you need to change the approach by using GD library functions by doing some what like this
$img = imagecreatefrompng($imgPath); // load the image
list($width,$height) = getimagesize($imgPath); // get its size
$c = imagecolortransparent($img,imagecolorallocate($img,255,1,254)); // create transparent color, (255,1,254) is a color that won't likely occur in your image
$border = 10;
imagefilledrectangle($img, $border, $border, $width-$border, $height-$border, $c); // draw transparent box
imagepng($img,'after.png'); // save
I Could see a similar requirement which is posted in another forum here
Try
$canvas1->setImageOpacity(0);
I am trying to replicate the functionality that Dribbble.com does with detecting the predominant colors in an Image. In the image below you can see a screenshot from Dribbble.com that shows the 8 predominant colors in the image to the left. Here is the actual page in the image http://dribbble.com/shots/528033-Fresh-Easy?list=following
I need to be able to do this in PHP, once I get the colors I need I will save them to a database so the processing does not need to be run on every page load.
After some research on how to get these colors out of an Image, some people said you simply examine an image pixel by pixel and then save the colors that occur the most. Other say there is more to it and that getting the colors that exist the most frequent won't give the desired affect. They say you need to Quantize the image/colors (I am lost at this point).
In the image below the Dribble shot below is a Javascript library that does the same thing, that page can be viewed here http://lokeshdhakar.com/projects/color-thief/
Viewing the source of that page I can see there is a Javascript file named quantize.js and the results are really good. So I am hoping to be able to do what that Javascript library does but with PHP and GD/ImageMagick
I had found this function that will return the colors and count in an Image with PHP but the results are different from the Javascript version above and the Dribble results
/**
* Returns the colors of the image in an array, ordered in descending order, where the keys are the colors, and the values are the count of the color.
*
* #return array
*/
function Get_Color()
{
if (isset($this->image))
{
$PREVIEW_WIDTH = 150; //WE HAVE TO RESIZE THE IMAGE, BECAUSE WE ONLY NEED THE MOST SIGNIFICANT COLORS.
$PREVIEW_HEIGHT = 150;
$size = GetImageSize($this->image);
$scale=1;
if ($size[0]>0)
$scale = min($PREVIEW_WIDTH/$size[0], $PREVIEW_HEIGHT/$size[1]);
if ($scale < 1)
{
$width = floor($scale*$size[0]);
$height = floor($scale*$size[1]);
}
else
{
$width = $size[0];
$height = $size[1];
}
$image_resized = imagecreatetruecolor($width, $height);
if ($size[2]==1)
$image_orig=imagecreatefromgif($this->image);
if ($size[2]==2)
$image_orig=imagecreatefromjpeg($this->image);
if ($size[2]==3)
$image_orig=imagecreatefrompng($this->image);
imagecopyresampled($image_resized, $image_orig, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); //WE NEED NEAREST NEIGHBOR RESIZING, BECAUSE IT DOESN'T ALTER THE COLORS
$im = $image_resized;
$imgWidth = imagesx($im);
$imgHeight = imagesy($im);
for ($y=0; $y < $imgHeight; $y++)
{
for ($x=0; $x < $imgWidth; $x++)
{
$index = imagecolorat($im,$x,$y);
$Colors = imagecolorsforindex($im,$index);
$Colors['red']=intval((($Colors['red'])+15)/32)*32; //ROUND THE COLORS, TO REDUCE THE NUMBER OF COLORS, SO THE WON'T BE ANY NEARLY DUPLICATE COLORS!
$Colors['green']=intval((($Colors['green'])+15)/32)*32;
$Colors['blue']=intval((($Colors['blue'])+15)/32)*32;
if ($Colors['red']>=256)
$Colors['red']=240;
if ($Colors['green']>=256)
$Colors['green']=240;
if ($Colors['blue']>=256)
$Colors['blue']=240;
$hexarray[]=substr("0".dechex($Colors['red']),-2).substr("0".dechex($Colors['green']),-2).substr("0".dechex($Colors['blue']),-2);
}
}
$hexarray=array_count_values($hexarray);
natsort($hexarray);
$hexarray=array_reverse($hexarray,true);
return $hexarray;
}
else die("You must enter a filename! (\$image parameter)");
}
So I am asking if anyone knows how I can do such a task with PHP? Possibly something exist already that you know of or any tips to put me a step closer to doing this would be appreciated
Here's exactly what you're looking for in PHP: https://github.com/thephpleague/color-extractor
Example :
use League\ColorExtractor\Palette;
$palette = Palette::fromFilename('some/image.png');
$topEightColors = $palette->getMostUsedColors(8);
This is my simple method to get the main color of an image
$image=imagecreatefromjpeg('image.jpg');
$thumb=imagecreatetruecolor(1,1);
imagecopyresampled($thumb,$image,0,0,0,0,1,1,imagesx($image),imagesy($image));
$mainColor=strtoupper(dechex(imagecolorat($thumb,0,0)));
echo $mainColor;
You need to scale down the picture and you will get the main colors of the picture. If you need 4 colors in the pallet, scale it down to about 8x8, 6 colors to about 12x8 and so on...
imagecopyresized for scaled down image then check every pixels and store them in array imagecolorat($image,px,py)
Try this out
<?php
// EXAMPLE PICTURE
$url='https://www.nordoff-robbins.org.uk/sites/default/files/google.jpg';
//var_dump(getColorPallet($url));
echoColors(getColorPallet($url));
function echoColors($pallet){ // OUTPUT COLORSBAR
foreach ($pallet as $key=>$val)
echo '<div style="display:inline-block;width:50px;height:20px;background:#'.$val.'"> </div>';
}
function getColorPallet($imageURL, $palletSize=[16,8]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE
// SIMPLE CHECK INPUT VALUES
if(!$imageURL) return false;
// IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE
$img = imagecreatefromjpeg($imageURL);
// SCALE DOWN IMAGE
$imgSizes=getimagesize($imageURL);
$resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]);
imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]);
imagedestroy($img);
//CHECK IMAGE
/*header("Content-type: image/png");
imagepng($resizedImg);
die();*/
//GET COLORS IN ARRAY
$colors=[];
for($i=0;$i<$palletSize[1];$i++)
for($j=0;$j<$palletSize[0];$j++)
$colors[]=dechex(imagecolorat($resizedImg,$j,$i));
imagedestroy($resizedImg);
//REMOVE DUPLICATES
$colors= array_unique($colors);
return $colors;
}
?>
Works perfect for me.
The page you linked to has a link to the source code on GitHub so if you want to know exactly how they are doing you could replicate their source in PHP.
The big difference between how they are doing it and how you are doing it, is that they are using clustering to find the color. Instead of rounding the color when they store it, they are storing all of the raw colors in an array. Then they loop through this array until they find a cluster that has the highest ratio of points in the cluster to number of colors in the cluster. The center point of this is the most common color. The palette is then defined by the next highest sets of clusters, with some logic to prevent near complete overlap of the clusters.
Try this: http://www.coolphptools.com/color_extract
Works with JPEG and PNG.
And best!: no hustle with composer, just require_once
require_once 'colorextract/colors.inc.php';
$ex=new GetMostCommonColors();
$num_results=20;
$reduce_brightness=1;
$reduce_gradients=1;
$delta=24;
$colors=$ex->Get_Color( 'image.png', $num_results, $reduce_brightness, $reduce_gradients, $delta);
print_r($colors);
give you something like this:
Array (
[3060a8] => 0.55827380952381
[f0a848] => 0.19791666666667
[000000] => 0.069642857142857
[483018] => 0.02047619047619
[786018] => 0.01827380952381
[183060] => 0.01797619047619
[4878a8] => 0.016011904761905
[181800] => 0.015119047619048
[a87830] => 0.014345238095238
[a8c0d8] => 0.011904761904762
[6090c0] => 0.01172619047619
[d89030] => 0.011011904761905
[90a8d8] => 0.0071428571428571
[ffffff] => 0.0070238095238095
[604830] => 0.006547619047619
[f0f0f0] => 0.0063095238095238
[d8d8f0] => 0.005297619047619
[c0d8d8] => 0.0044047619047619
[f0f0ff] => 0.00041666666666667
[181830] => 0.00011904761904762 )
I tried it with different images and it seems reliable.
The idea of getting the predominant colors of the image is a bit tricky, because for example the most frequent pixel color could be so widely scattered in the image that it is not perceived as a predominant color at all.
I think an algorithm like Color coherence vector will be good enough to overcome this issue, because it clusters the colors into coherent and incoherent (which is quite intuitive), and then you can use them to discard those false positive predominant colors.
I see it is an easy algorithm to implement, this tutorial Image Retrieval: Color Coherence Vector describes describes its steps with examples of how it works and there is even a matlab implementation mentioned at the end of it.
I have a Unix bash shell script with ImageMagick called dominantcolor that may do what you want. See my scripts web site at http://www.fmwconcepts.com/imagemagick/index.php. You an run it from PHP exec(). See my pointers for use on my home page.
Input:
dominantcolor -n 6 -p all -s save plate.png
count,hexcolor
586,#5ECADC
520,#AFA85D
469,#3C3126
462,#B9C8BB
258,#488A70
205,#B06928
The -n 6 is the desired number of colors in the color quantization. The -p all means print all counts and colors for the resulting 6 colors. The -s save indictates to save a swatch image.
Colors below are shown with the dominant color on the left and decreasing count colors towards the right according to the list above.