I've got an image and want to remove all whitespace around it, and then save it as a transparent PNG. I'm using Imagick in PHP to do so, but my script doesn't seem to function properly.
<?php
$im = new Imagick("http://images.icecat.biz/img/norm/high/14688888-2862.jpg");
$im->borderImage("#ffffff", 20, 20);
$im->trimImage(0.3);
$im->setImagePage($im->getImageWidth(), $im->getImageHeight(), 0, 0);
$im->setImageFormat("png");
header("Content-Type: image/" . $im->getImageFormat());
echo $im->getImageBlob();
?>
What do I need to do to remove all white (and close to white) areas at the borders? And when that is done, can I easily resize the image to crop all of the transparency?
The fuzz factor needs to be a quantum scaled value, not just for this function but almost all functions that take 'fuzz' as a parameter.
i.e. you need to scale it up to the quantum range.
$im->trimImage(0.3 * \Imagick::getQuantum());
Or if you are using an earlier version of Imagick that doesn't have that method, then instead do:
$range = $image->getQuantumRange();
$image->trimImage(0.3 * $range['quantumRangeLong']);
The reason for this is to allow precise control over the pixel matching. If the value was passed in as a float value in the range 0-1 it would not possible to have exact control over the value that was used for matching.
By instead using an integer value (for versions of Imagick that do not have HDRI enabled) it allows you to precisely control the values that are compared for the operation.
You need something like an autocrop based on pixel values, I think this will help:
http://www.imagemagick.org/script/command-line-options.php#trim
you might also like:
http://fmwconcepts.com/imagemagick/autotrim/index.php
source:
http://www.imagemagick.org/discourse-server/viewtopic.php?t=10843
Related
My goal
I have an existing PNG. It currently has anti-aliasing, or in other words, shades of gray. I want the image to be 1 bit, or in other words, only using the colors black and white. My aim is to do this with PHP GD. I have to do this with an existing image, and can not create the image from scratch using imagecreatetruecolor.
What I'm trying
The function I've found that seems best for the job is imagetruecolortopalette
http://php.net/manual/en/function.imagetruecolortopalette.php
Here is a simple version of what I'm trying to do
$user_design = base64_decode($_POST['input']);
$design_file = fopen('path/filename.png', 'w') or die("Unable to open file!");
imagetruecolortopalette($design_file, false, 1);
fwrite($design_file, $user_design);
fclose($design_file);
With this being the key line. The 1 being the "maximum number of colors that should be retained in the palette."
imagetruecolortopalette($design_file, false, 1);
Behavior I'm getting
The image appears unchanged. I'm not sure if I'm using PHP GD correctly, or if this function doesn't do what I think it does.
Other ideas
These also seem promising.
imagecolordeallocate seems like I may be able to use it to deallocate colors, but not sure how to do this without calling it 254 times.
http://php.net/manual/en/function.imagecolordeallocate.php
imagecolorset seems like I may be able to use it to set the palette, but I'm not sure how to do this for existing images.
http://php.net/manual/en/function.imagecolorset.php
Mostly I suspect imagetruecolortopallette is the best bet, but any and all ideas welcome.
$im = imagecreatefromstring($user_design);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -1000);
imagepng($im, 'path/filename.png');
imagedestroy($im);
How do you convert an image to black and white in PHP
I am trying to add round corners to a jpeg file, but the problem is that after adding round corners, I am getting a black background color. Somehow I am not able to change it to any other color (white, transparent, red). It just simply shows black background where the image has rounded corners.
The code that I am using is:
<?php
$image = new Imagick('example.jpg');
$image->setBackgroundColor("red");
$image->setImageFormat("jpg");
$image->roundCorners(575,575);
$image->writeImage("rounded.jpg");
header('Content-type: image/jpeg');
echo $image;
?>
I cannot use png as the jpeg files are huge, about 5 MB, so if I used png, the file size would go up to 26 MB, even though the png adds transparent round corners.
Also the IMagick version that i am using is:
ImageMagick 6.6.2-10 2010-06-29 Q16 http://www.imagemagick.org
Also the output(image generated) will get printed so I don't know if css will work over here.
Sorry, I am trying to actually create a new jpeg file with rounded corners from an already existing jpeg file that doesn't have round corners this is actually a photograph taken from a camera, so there are multiple/too many colors so I can't use gif as well.
Also my site will only just generate the round corner image then afterwards it will get downloaded using a FTP program by the admin of the site and then using a system software will get printed, so in short my website will not be printing the image but rather just generate it
Try this:
<?php
$input = 'example.jpg';
$size = getimagesize($input);
$background = new Imagick();
$background->newImage($size[0], $size[1], new ImagickPixel('red'));
$image = new Imagick($input);
$image->setImageFormat("png");
$image->roundCorners(575,575);
$image->compositeImage($background, imagick::COMPOSITE_DSTATOP, 0, 0);
$image->writeImage("rounded.jpg");
?>
I may get downvoted, but I say let css deal with the corners and take some load off of your server :)
CSS rounded corners.
JPG doesn't have a transparent color(s) (alpha channels) in its palette.
The output image must use either PNG or GIF (or another image format that supports alpha channels).
setImageBackgroundColor is another option if you want an opaque background.
EDIT
Your comment reminds me that you could try to use the command line; shell_exec() will run a command line argument from PHP. The command in the ImageMagick API you'll need to start with is convert example.jpg, and then you can pass flags with the various parameters you want.
Since ImageMagick is already installed, it will work right away. You may need to point your system PATH to the ImageMagick directory where all of the executables are.
There's plenty of questions and forums dedicated to rounded corners with this method so I'll leave that up to you.
Here's a helpful tip though - there is a silly confusion with the convert command, since Windows also has a convert.exe that is rarely used, but will confuse your command line, so make sure you're calling the right convert. ;) To test if it's working, try convert example.jpg example.gif (which should convert your example to a gif).
To get output from your command line, finish all commands with 2>&1 which will pipe cmd output back into PHP.
I've been bashing my head agains something simple..
// ....all prev code is fine....
$pasteboard =imagecreatetruecolor($imgs['bg']["width"],$imgs['bg']["height"]);
imagealphablending($pasteboard, false);
imagecopyresampled($pasteboard, $imgs['bg']["img"],0,0,0,0,$imgs['bg']["width"],$imgs['bg']["width"],imagesx($imgs['bg']["img"]),imagesy($imgs['bg']["img"]));
imagecopyresampled($pasteboard, $imgs['photo']["img"],20,20,0,0,$imgs['photo']["width"],$imgs['photo']["width"],imagesx($imgs['photo']["img"]),imagesy($imgs['photo']["img"]));
imagesavealpha($pasteboard,true);
//send it out
$out = $pasteboard;
header('Content-type: image/png');
imagepng($out);
//then garbage collection
gives me this:
HORAY!
perfect alpha png composite...
Now I want to rotate it, so instead of the $out=$pasteboard i do this:
imagesavealpha($pasteboard,true);
//rotate it
$out = imagerotate($pasteboard,5,imagecolorexactalpha($pasteboard,255,255,255,50),0);
header('Content-type: image/png');
imagepng($out);
which sadly gives me this:
BOOOO!
Ive tried setting the color like:
imagerotate($pasteboard,5,0x00000000,0);
also the last attr like:
imagerotate($pasteboard,5,0x00000000,1);
new empty images sampled etc etc...
no dice....
Can anyone help?
I'm answering my question simply because I've tried 10-15 suggestions i've seen allover the web all of which offering 'nearly' right solutions but nothing exact, Also I've seen this question posted a few places now, and hopefully if anyone reaches this page in future it would be best to show the solution as the direct answer.
MASSIVE thanks to #cristobal for the help and efforts, if I could vote you up any more I would !
The knack seems to be:
//rotate it
$pasteboard = imagerotate($pasteboard,5,0XFFFFFF00,0); //<-- here must be RRGGBBAA, also last attr set to 0
imagesavealpha($pasteboard, true); // <-- then to save it... dont ask me why..
//send it out
header('Content-type: image/png');
imagepng($pasteboard);
produces this (it has a perfect alpha even though you cant see against the white page):
REALLY not the most fun 5 hrs of my life... hopefully it will stop someone else going through the same pain..
Using the same code above and using a blue color for the third parameter in the imagerotate operation, which will be it used to fill the uncovered zone after the rotation i.e.:
imagerotate($pasteboard, 5, 255);
We get the following image
we see the blue area is the uncovered zone which it fills, while the black color is the to be the border shadow from the image which GD does not seem to handle well along the interpolation used in the rotation.
The same image rotated using the convert for imagemagick. commmand i.e. $> convert -rotate 5 image.png image_rotated.png results in the image below
Clearly GD does not handle alpha colors well when rotating.
If you have access to use the convert commmand using exec or process, you should pipe those image operation to imagemagick instead. GD is a simple image library which has not been updated much the latest years. Otherwise try Imagemagick, Cairo or Gmagick which there are pecl plugins for too http://php.net/manual/en/book.image.php.
Last resort somebody made a function that which uses GD http://www.exorithm.com/algorithm/view/rotate_image_alpha for what you are looking after but the result is not pretty since its a simple linear interpolation:
taken from How to rotate an image in GD Image Library while keeping transparency?. Perhaps if you convert the linear interpolation function to a Bicubic or Quad it will look better.
Note these answers did not work for me but this did.
$destimg = imagecreatefromjpeg("image.png");
$rotatedImage = imagerotate($destimg, 200, 0);
imagesavealpha($rotatedImage, true);
imagepng($rotatedImage,"rotated.png");
Is there any good function to calculate the pixel width and height? Can imagettfbbox be used to do that? I mean which ttf file is needed for the different fonts used by different browsers?
Thx
As PHP run's on the server there is no way to do that with PHP alone. The size of the text depends on the operating system, the browser (and the browser settings like zoom) of the client. You could however use javascript to get the size of an element once its rendered.
height = document.getElementById("elementId").style.height; // Will return 176px for example
width = document.getElementById("elementId").style.width; // Will return 176px for example
Hope this helps
There is a function (imagefontwidth and imagefontheight), but they only return the size of one character using the built-in fonts (which are all fixed-width). You'll get the width/height of the entire string by multiplying the number returned by the number of characters.
I don't know of any way that lets you get the width or height of a string using a custom font, but I'm interested in this too.
Hope this helps.
Would like to turn this into black and white.. can't figure out what to use from imagick..
$handle_data = file_get_contents('http://www.bungie.net/Stats/Reach/Nightmap.ashx');
//http://www.bungie.net/Stats/Halo3/Nightmap.ashx
$img = new Imagick();
$img->readImageBlob($handle_data);
$img->writeImage('nightmap/'.$time.'.gif');
Using Imagick::modulateImage could be a quick&dirty solution. Dirty because color theory is a rather complex field, and there can be done more to create grayscale images than just desaturating the image (like applying different weights to the single color channels).
bool Imagick::modulateImage (float $brightness , float $saturation , float $hue)
Given an image, keep brightness and hue at 100%, while setting saturation to 0%. There is an example at the bottom of the documentation page that does exactly that.
There's a much better (and just as simple) solution: $im = $im->fxImage('intensity');
That applies a function to the image, where intensity is equal to 0.299*red+0.587*green+0.114*blue.
That formula is based on how our eyes are more sensitive to different colours, and as such the difference between that and a "flat" grayscale image really is night and day.
More details here:
http://php.net/manual/en/imagick.fximage.php
http://www.imagemagick.org/script/fx.php