I'm trying to piece together a png from various components of an svg file using Imagick. I am able to get the text in and behaving as expected. Now how can I start adding the various svg components. In the example below, I have a sample variable with a string that represents my svg element. I have to use SVG element formatting and attributes, like r, may occasionally be set by variables.
Edit: Big picture, I'm just converting an svg with some dynamic settings to a png.
<?php
//SVG ELEMENT TO INCORPORATE
$element = '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />';
//MESSAGE
$message = "Get this SVG to work.";
//FILENAME
$fileName = "testSVG" . microtime(true) . ".png";
//SET THE SIZE, BACKGROUND, AND FORMAT
$image = new Imagick();
$image->newImage(1200, 630, new ImagickPixel('pink'));
$image->setImageFormat('png');
//NEW DRAW ELEMENT
$draw = new ImagickDraw();
//FONT PROPERTIES
$draw->setFont('Impact.ttf');
$draw->setFontSize(50);
$draw->setFillColor("red");
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
//FONT METRICS
$metrics = $image->queryFontMetrics($draw, $message);
//ADD TEXT TO CANVAS
$draw->annotation(5, $metrics['ascender']+5, $message);
//DRAW THE IMAGE
$image->drawImage($draw);
//SAVE THE IMAGE
file_put_contents($fileName, $image);
//DISPLAY THE IMAGE
header('Content-type: image/png');
echo $image;
?>
Related
I am able to successfully resize (to the proper resized dimensions) an image that I have created from one page of a pdf document. However, I do not understand why the result is a dark resized image with a patch of white. Please, can someone advise?
PHP code:
// Create image from first page of pdf document
$im = new imagick('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
$imageHeight = $im -> getImageHeight();
$imageWidth = $im -> getImageWidth();
$desiredImgWidth = 200;
$desiredImgHeight = resizedImageHeight($imageWidth, $imageHeight,
$desiredImgWidth);
$im -> resizeImage($desiredImgWidth, $desiredImgHeight,
imagick::STYLE_NORMAL, 1);
// Save image
$page = '1';
$saveToFolder = 'thumbnailFolder';
$fileName = 'thanhThumbNail_'.$page.'.jpg';
$saveImgToPath = $saveToFolder.'/'.$fileName;
$result = file_put_contents($saveImgToPath, $im);
function resizedImageHeight($imgWidth, $imgHeight, $desiredImgWidth){
$quoient = $imgWidth/$imgHeight;
$height = $desiredImgWidth/$quoient;
return $height;
}
Resulting thumbnail image:
Link to original PDF can be found here:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4905263/pdf/ksgt-06-04-1091539.pdf
Your PDF has transparency. JPG does not support transparency and shows black where the PDF was transparent. Just turn the transparency off. In Imagemagick command line:
convert -density 300 ksgt-06-04-1091539.pdf[0] -alpha off result.jpg
See setImageAlphaChannel at http://us3.php.net/manual/en/imagick.setimagealphachannel.php
Looks like the background color is not defined. You need to set the background color before reading the PDF document.
// Create image from first page of pdf document
$im = new imagick();
$im->setBackgroundColor('WHITE');
$im->readImage('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
I am developing image editor, i successfully write text on images on position x,y, now i need to draw a white image on image that is called white out. white image will be drawn at position cord X, cord Y and dynamic size of image width, height. i write code but i am not getting the image on right coordinates and height width of image.
here is my image rendering function.
$image = new Imagick('image.jpg');
$diagnose=$this->input->post('diagnoses');
$fontsize=$this->input->post('fontsize');
$fontstyle=$this->input->post('fontstyle');
$cordX = $this->input->post('posX');
$cordY = $this->input->post('posY');
$font_size = 20;
// Watermark text
//$diagnose = "Hello world.{newline}It's a beautiful day.";
$textlinesArray = explode("{newline}",$diagnose);
// Create a new drawing palette
$draw = new ImagickDraw();
// Set font properties
$draw->setFont('Arial');
$draw->setFontSize($font_size);
$draw->setFillColor('black');
// Position text at the bottom-right of the image
$draw->setGravity(Imagick::GRAVITY_NORTHWEST);
$i = 0;
foreach ($textlinesArray as $index => $text) {
$newY = ($i * $font_size) + $cordY;
//echo $newY . "</br>";
//echo $text;
// Draw text on the image
$image->annotateImage($draw, $cordX, $newY,0, $text);
$i++;
}
$draw->setFillColor('magenta'); // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'cyan' ) );
$draw->setStrokeWidth(2);
$draw->rectangle($cordX, $cordY, 200, 300); // Draw the rectangle
$image->drawImage( $draw );
// Set output image format
$image->setImageFormat('png');
// Output the new image
header('Content-type: image/png');
echo $image;
here is the output, i need that color box dynamic width height and position
I followed this example to embed text in image while uploading it but it's not working.
This is my code:
header('Content-type: image/jpeg');
$img = $_FILES['mainImage']['name'];
list($txt, $ext) = explode(".", $img);
$imgName = "ac_".time().".".$ext;
$tmp = $_FILES['mainImage']['tmp_name'];
$textToImage = imagecreatefromjpeg($tmp);
// Allocate A Color For The Text
$white = imagecolorallocate($textToImage, 255, 255, 255);
// Set Path to Font File
$font_path = '../assets/fonts/font.ttf';
// Set Text to Be Printed On Image
$text = "Test text";
// Print Text On Image
imagettftext($textToImage, 25, 0, 75, 300, $white, $font_path, $text);
$imageUploaded = move_uploaded_file($tmp, 'images_path/'.$imgName);
if(!$imageUploaded){
die('Error upload image!');
}
The image is uploaded but wihout text in it !
For this we are working with GD library.
"PHP is not limited to creating just HTML output. It can also be used
to create and manipulate image files in a variety of different image
formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more
convenient, PHP can output image streams directly to a browser. You
will need to compile PHP with the GD library of image functions for
this to work. GD and PHP may also require other libraries, depending
on which image formats you want to work with."
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.
The following code sample demonstrates the use of GD library to watermark images on the fly. The method demonstrated here to watermark an uploaded image is to overlay the original image with another image, preferably a transparent PNG image.
PHP provides a rich set of functions to create and alter images on the fly. These functions require the GD library, which is bundled with PHP since version 4.3.
The HTML form needs a file upload element: <input type="file">. You must also specify the correct encoding type: enctype="multipart/form-data" for the form.
/ link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;
function create_image($user){
global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";
// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {
// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);
// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;
// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;
}
// create the image
imagejpeg($im, $file, $quality);
}
return $file;
}
function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}
$user = array(
array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),
array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),
array(
'name'=> 'SlimenTunis#webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);
// run the script to create the image
$filename = create_image($user);
here we have two functions to make it as simple as possible. To run the code simply pass the $user array data to the function and it’ll save the new image in the folder ‘covers’ on your server. The function returns the file url so you just need to echo it into an image tag as shown below. Check out the demo where you can create your own.
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>
You can try using the Intervention library. I use it for doing what you're asking about. It is quite simple to understand and the documentation is is well-written.
I am creating a custom blog with php. when the user is uploading an article I am having problem with the images in the post. some images's width are bigger than the main div in my blog (740). I want to use php to check the width of the images if it is bigger than 740 then re-size the image to 740.
<?php
$dom = new domDocument;
$dom->loadHTML($article_content);
$dom->preserveWhiteSpace = false;
$imgs = $dom->getElementsByTagName("img");
$links = array();
for($i=0;$i<$imgs->length;$i++){
$links[] = $imgs->item($i)->getAttribute("width");
$image_path = $links[];
$article_source = imagecreatefromstring(file_get_contents($image_path));
$image_width = imagesx($image_source);
if($image_width > 740){$image_width = 740;}
}
?>
so far this is the code that I have. I am not sure how to set the image width.(the image already has its original width)
UPDATE:
I am not trying to save or copy the image. I am trying to access the dom by php and set the image width to $image_width (of all images)
From your code I assume that you are using the GD library. In that case, what you are looking for is imagecopyresized().
Here's an example of what you might want if the image width is too great:
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($small_image, $image_source,
0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
Then $small_image will contained the scaled version of the image.
Without saving/copying the image you will have to replace img tags in the HTML document with ones having a width attribute.
$dom = new domDocument;
$dom->loadHTML($article_content);
$imgElements = $dom->getElementsByTagName("img");
foreach ($imgElements as $imgElement) {
$imgSrc = imagecreatefromstring(file_get_contents($imgElement->getAttribute("src")));
if (imagesx($imgSrc) > 740) {
// we replace the img tag with a new img having the desired width
$newE = $dom->createElement('img');
$newE->setAttribute('width', 740);
$newE->setAttribute('src', $imgElement->getAttribute("src"));
// replace the original img tag
$imgElement->parentNode->replaceChild($newE, $imgElement);
}
}
// html with "resized" images
echo $dom->saveHTML();
I am creating an image with a caption using the Imagick::newPseudoImage function as follows:
$txt = new Imagick();
$txt->setFont("templates/fonts/Gloria.ttf");
$txt->setGravity(imagick::GRAVITY_CENTER);
$txt->newPseudoImage( $image_width, $image_height, "caption:" . $text );
This draws a black caption. I want to customize the color of this caption. I know there are other methods of drawing text with Imagick. I need to use the newPseudoImage with caption instead of these other methods because it automatically wraps and sizes the text to fit in a given rectangle.
colorizeImage has issues will making a slightly darker version of the text becuase it blends funny with the black. Use clutImage instead.
$txt = new Imagick();
$txt->setFont("templates/fonts/Gloria.ttf");
$txt->setGravity(imagick::GRAVITY_CENTER);
$txt->newPseudoImage( $image_width, $image_height, "caption:" . $text );
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('#0000b0'));
$txt->clutImage($clut);
$clut->destroy();
You can use colorizeImage. I hope this can help you:
$im = new Imagick();
$background = new ImagickPixel('none');
$im->setBackgroundColor($background);
$im->setFont("somefont.ttf");
$im->setpointsize(72);
$im->setGravity(Imagick::GRAVITY_CENTER);
$im->newPseudoImage(300, 300, "caption:" . "Put your text" );
$im->colorizeImage('#0000b0',1.0);
$im->setImageFormat("png");
header( "Content-Type: image/png" );
echo $im;