I'm sorry for my English!
I've this problem with imagick php and overlay text on an image.
Size of font is small when resize the width of image.
This is an example for two image width, first is 350px and second is 1728px:
http://i.stack.imgur.com/8kRo0.jpg
http://i.stack.imgur.com/TedDO.jpg
$f->userFontSize is the size of font that logged user choose to show on his image.
if(trim($_GET['full']) != 'si'){
$width = 350;
$height = 350;
} else {
$width = getWidth($root . $f->imagePathFull);
$height = getHeight($root . $f->imagePathFull);
}
$image = new imagick();
$draw = new imagickDraw();
$pixel = new imagickPixel('white');
$image->newImage($width, $height, $pixel);
$image->readImage($root . $f->imagePathNormal);
$image->resizeImage ( $width, $height, imagick::FILTER_LANCZOS, 1, TRUE);
$fontPath = $root . '/assets/fonts/Mermaid.ttf';
$draw->setFillColor('black');
$draw->setFont($fontPath);
$draw->setFontSize(12 + $f->userFontSize);
$draw->setGravity(1);
$draw->setTextAntialias(true);
$draw->setFillOpacity(".55");
$image->annotateImage($draw, 5,0, 0, "text text text");
$image->setImageFormat("jpg");
header( "Content-Type: image/jpeg" );
echo $image->getImageBlob();
$image->clear();
When I print the image with resolution as 1728px the text is very small. How I do to do to increase font size depending image size?
Thank you! :)
I've solved with this way, I calculated the percentage of width that text occupy on image at 350px and according to this I calculated the percentage at 1728px(or another width). I do cicle a some font size until when I find a size that is egual at percentage. The final result of my solution is non perfect but acceptable. This is the code:
$myCP = '40'; // increase o decrease font size.
for($i = 1; $i <= 500;$i++){
$box = imagettfbbox($i, 0, $fontPath, "lorem ipsum");
$lT = $box[2] - $box[0];
$cP = round(($lT / $width) * 100,1);
// $cP percentage of font width
if($cP >= $myCP) { $newFontSize = $i; break; } else { continue; }
}
Related
I want to cut out part of the photo without stretch it.
Something like the photo I posted, cut out the red part and get photo number 2
With a width of 150px and height of 100px and cuting from top left of photo
enter image description here
I tried to do it with this code but it didn't work.
This codes separates part of the image, but does not do so from the top left of the image.
function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
// set destination directory
if (!$newdir) $newdir = $dir;
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image?
if ($or_w > $max_w || $or_h > $max_h) {
// resize by height, then width (height dominant)
if ($max_h < $max_w) {
$rs_h = $max_h;
$rs_w = $rs_h / $ratio;
}
// resize by width, then height (width dominant)
else {
$rs_w = $max_w;
$rs_h = $ratio * $rs_w;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
}
// image requires no resizing
else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $newdir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 2) - ($th_w / 2));
$new_h = (($rs_h / 2) - ($th_h / 2));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $newdir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
$dir = './';
$img = '1.jpg';
$size = getimagesize($img);
$width = $size[0];
$height = $size[1];
resizejpeg($dir, '', $img, $width, $height, 150, 100);
I didn't understand correctly what you mean, but based on your description you are trying to get the image no 2 which means you are trying to crop an image. If that your mean, maybe this code will help
function crop($image_path, $output_path, $x, $y, $width, $height) {
// load image
$image = imagecreatefromjpeg($image_path);
// crop the image
$cropped_image = imagecrop($image, [
'x' => $x,
'y' => $y,
'width' => $width,
'height' => $height
]
);
// save it
imagejpeg($cropped_image, $output_path);
}
you can use it like this
// input image path
$image = "img.jpg";
// output image path
$output = "crop_img.jpg";
// crop it from (0,0)
crop($image, $output, 0, 0, 150, 100);
in my project i just do image watermarking or image combine it's working fine and code for that.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['submit']))
{
// Give the Complete Path of the folder where you want to save the image
$folder="uploads/";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "$folder".$_FILES["fileToUpload"]["name"]);
$file='uploads/'.$_FILES["fileToUpload"]["name"];
$uploadimage=$folder.$_FILES["fileToUpload"]["name"];
$newname= time();
$ext = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION);
// Set the thumbnail name
$thumbnail = $folder.$newname.".".$ext;
$imgname=$newname.".".$ext;
// Load the mian image
if ($ext=="png" || $ext=="PNG") {
$source = imagecreatefrompng($uploadimage);
}
else if ($ext=="gif" || $ext=="GIF") {
$source = imagecreatefromgif($uploadimage);
}
else if ($ext=="bmp" || $ext=="BMP") {
$source = imagecreatefrombmp($uploadimage);
}
else{
$source = imagecreatefromjpeg($uploadimage);
}
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($source)/2;
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
$im_middle_w = $main_width/2;
$im_middle_h = $main_height/2;
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = $im_middle_w - $water_width/2;
$dime_y = $im_middle_h - $water_height/2;
// copy both the images
imagecopy($source, $watermark, $dime_x, $dime_y, 0, 0, $water_width, $water_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
unlink($file);
}
?>
<img src='uploads/<?php echo $imgname;?>'>
</body>
</html>
but problem with setting $water_width and i want set as half of my source image. but when i have source image of less width or more width compare to $water_width it's set it like that. see image when source image width is more.
and when width is less.
so my problem is how to set $water_width as half of source image width?
by Alex your answer it's came up like this.
This will resize watermark to half-width of original image and put it in the centre:
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($watermark);
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
// resize watermark to half-width of the image
$new_height = round($water_height * $main_width / $water_width / 2);
$new_width = round($main_width / 2);
$new_watermark = imagecreatetruecolor($new_width, $new_height);
// keep transparent background
imagealphablending( $new_watermark, false );
imagesavealpha( $new_watermark, true );
imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_width, $new_height, $water_width, $water_height);
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = round(($main_width - $new_width)/2);
$dime_y = round(($main_height - $new_height)/2);
// copy both the images
imagecopy($source, $new_watermark, $dime_x, $dime_y, 0, 0, $new_width, $new_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
imagedestroy($source);
imagedestroy($watermark);
imagedestroy($new_watermark);
You can try imagettftext method, if you don't want any such high perfection in transparency. You can have try of this code. You have to save a font file in your directory, here I used arial.ttf.
$im = imagecreatefrompng("png.png"); //create image data
$font = 'arial.ttf'; //font file name
$randomString = "example.com"; //string need to be shown
$main_width = imagesx($im); //finding width and height
$main_height = imagesy($im);
$posx= $main_width/2; //finding center
$posy = $main_height/2;
$color = imagecolorallocate($im, 200, 200, 200); //Creating color
$size = ($main_width/25)+1; //determine size of font. +1 to avoid 0
$temp = $size*5;
$posx = $posx-$temp; //adjust to average center
imagettftext($im,$size,0, $posx, $posy, $color, $font , $randomString); //apply a text
You have to adjust posx and posy for your text position. Size also can be adjusted with some logics.
$color = imagecolorallocate($im, 0, 0, 0);= black
and $color = imagecolorallocate($im, 255, 255, 255); = white.
You have to adjust this for your required text color.
I have the below script, it all works fine, apart from if I enter a value into the function arguments for the percentage, the overlay's are too large, they should scale down by #% of the max size.
Here is an example:
But then if I change the "80" to "0" in the function call I get this:
If I change the same value to lets say "20" to scale the overlay down by 20%, I simply get the same as above...
Any ideas as to why it isn't scaling the overlay down by inputted %?
<?php
session_start();
//Set the content-type
header('Content-Type: image/png');
//Overlay URLS
$overlay_url = $_SESSION['ROOT_PATH']."images/logos/overlay.png";
$logo_url = $_SESSION['ROOT_PATH']."images/logos/".$_GET['logo'].".png";
//How much of the image will the overlays take up
$logo_percent = 0.60;
$overlay_percent = 0.90;
//Get the image size first
$size = explode(",",$_GET['size']);
$width = (int)$size[0];
$height = (int)$size[1];
$background = imagecreatetruecolor($width,$height);
$bg_color = imagecolorallocate($background,20,100,255);
imagefill($background, 0, 0, $bg_color);
//Apply company logo first
$company_logo = apply_watermark($background,$overlay_url,80,0,0,90);
//Now venue logo
imagepng(apply_watermark($company_logo,$logo_url,80,1,0,90));
//background(url/resource), watermarl(url), size percent, left0/right1, padding(px),rotate
function apply_watermark($bg,$wt,$p,$lr,$pad=0,$rt=false) {
//Load background image into memory,can apply more watermarks to same image
if (gettype($bg) == "resource") {
$background = $bg;
} else {
$background = imagecreatefromjpeg($bg);
}
//Get the width and height and generate watermark max size
$bx = imagesx($background);
$by = imagesy($background);
$overlay_max = (($bx > $by) ? $bx : $by) / 100 * $p;
//Create container for image
$imagecontainer = imagecreatetruecolor($bx,$by);
//Allow alpha channels to be saved and fill it with alpha
imagesavealpha($imagecontainer,true);
$alphacolor = imagecolorallocatealpha($imagecontainer,0,0,0,127);
imagefill($imagecontainer,0,0,$alphacolor);
//Copy background image into the container
imagecopyresampled($imagecontainer,$background,0,0,0,0,$bx,$by,$bx,$by);
//Load the watermark
$overlay = imagecreatefrompng($wt);
if($rt != false){$overlay = imagerotate($overlay,$rt,0);}
//get the watermark width and height and generate the aspect ratio
$ratio = $overlay_max / imagesx($overlay);
if ($ratio > ($bx / $by)) {
$scale = imagesx($overlay) / $bx;
} else {
$scale = imagesy($overlay) / $by;
}
$newwidth = (int)(imagesx($overlay) / $scale);
$newheight = (int)(imagesy($overlay) / $scale);
//Create container for the watermark and apply alpha to it
$newoverlay = imagecreatetruecolor($newwidth,$newheight);
imagesavealpha($newoverlay,true);
imagefill($newoverlay,0,0,$alphacolor);
//Copy the watermark to the watermark container with alpha
imagecopyresized($newoverlay, $overlay, 0, 0, 0, 0, $newwidth, $newheight, imagesx($overlay), imagesy($overlay));
//Copy the watermark to the background image container, choose left or right
if ($lr == 0) {
imagecopyresampled($imagecontainer,$newoverlay,0+$pad,($by-$newheight-$pad),0,0,$newwidth,$newheight,$newwidth,$newheight);
} elseif ($lr == 1) {
imagecopyresampled($imagecontainer,$newoverlay,($bx-$newwidth-$pad),($by-$newheight-$pad),0,0,$newwidth,$newheight,$newwidth,$newheight);
}
//Return the generated image back to the function call to further handle
return $imagecontainer;
}
?>
I'm using a url link to resize images, such as:
image.php?name=butterfly&size=1100x1100
for example:
<img src="image.php?name=butterfly&size=1100x1100">
The code I'm using is:
<?php
if(isset($_GET['name'])){ //name
$image['name'] = $_GET['name'];
} else {
$image['name'] = null;
}
if(isset($_GET['size'])){ //dimensions
$image['size'] = $_GET['size'];
$size = explode('x', $image['size']);
$image['width'] = $size[0];
$image['height'] = $size[1];
} else {
$image['size'] = null;
}
if(isset($_GET['text'])){ //text
$image['text'] = $_GET['text'];
} else {
$image['text'] = null;
}
// File and new size
$filename = 'images/'.$image["name"].'.jpeg';
// Content type
header('Content-Type: image/jpeg');
// Output
imagecreatefromjpeg($filename);
// Set a maximum height and width
$width = $image['width'];
$height = $image['height'];
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
My code works only for one part, which is the width, the image is resized to it's width but not height. Also when I resize my window, the picture get smaller every time. Thank you for your time and sorry for any bad explanation.
First of all, what is the question? I didn't get it.
One reason why the code changes only the width it may be because of this part of the code:
`if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}`
only one of the sizes will change. Also, another reasons why is changing only the width could be that you have as original image and quadratic resolution (e.g. 800x600 - ratio 1,34) and then you keep changing it to a wider one (e.g. 1280x720 - ratio 1,77).
Hope this helps!
As per your code logic, at any given time either your height or your width will change.
I tried it at my local host, width & height of my image was 600 X 400 and I passed 100X100 as parameter, it resized the image to 100X66, so the height did changed.
I want to reduce a picture size from 600px * 500px to 60px * 50px size, then crop it become 50px *50px. I have two groups of codes, 1 is to reduce the size of image, other 1 is to crop the image. The problem is they works separately, how to combine this two groups of codes to make them work together? Below is my codes :
<?php
//codes of group A - Reduce the size of image from 600px * 500px to 60px * 50px
$save2 = "images/users/" . $image_name_2; //This is the new file you saving
list($width2, $height2) = getimagesize($file) ;
$modwidth2 = 50;
$diff2 = $width2 / $modwidth2;
$modheight2 = $height2 / $diff2;
$tn2 = imagecreatetruecolor($modwidth2, $modheight2) ;
$image2 = imagecreatefromjpeg($file) ;
imagecopyresampled($tn2, $image2, 0, 0, 0, 0, $modwidth2, $modheight2, $width2, $height2) ;
imagejpeg($tn2, $save2, 100) ;
//codes of group B - Crop the image from 60px * 50px to 50px * 50px
$save3 = "images/users/" . $image_name_3;
list($width3, $height3) = getimagesize($file) ;
$modwidth3 = 60;
$diff3 = $width3 / $modwidth3;
$modheight3 = $height3 / $diff3;
$left = 0;
$top = 0;
$cropwidth = 50; //thumb size
$cropheight = 50;
$tn3 = imagecreatetruecolor($cropwidth, $cropheight) ;
$image3 = imagecreatefromjpeg($file) ;
imagecopyresampled($tn3, $image3, 0, 0, $left, $top, $cropwidth, $cropheight, $modwidth3, $modheight3) ;
imagejpeg($tn3, $save3, 100) ; //save the cropped image
?>
As you can see from 2 groups of codes above, 1st group resize the pic then save it to a folder. 2nd group of codes crop the pic then save it into the folder too. My question is ... After 1st group of codes resize the picture, is it necessary to save it into folder before I can crop it? If it is necessary, then I need to write new lines of codes to retrieve the resized pic from the folder for 2nd group of codes to crop it? If it is not necessary, after resizing the pic, how do I pass the pic to 2nd group of codes to crop it?
Here you are #zac1987.
Full PHP code generating square thumbnail of desired size without stretching image. The code supports both png and jpg/jpeg image extensions. Simply change settings part to desired one. You can copy paste the code and test it on your web server.
<?php
// SETTINGS
$image_name = 'file.jpg'; // Full path and image name with extension
$thumb_name = 'thumbnail'; // Generated thumbnail name without extension
$thumb_side = 100; // Desired thumbnail side size
// END OF SETTINGS
$image_extension = explode('.', $image_name); // I assume that images are named only following 'imagename.ext' pattern
if (preg_match('/jpg|jpeg/', $image_extension[1])) {
$src_image = imagecreatefromjpeg($image_name);
$image_extension = 'jpg';
} else if (preg_match('/png/', $image_extension[1])) {
$src_image = imagecreatefrompng($image_name);
$image_extension = 'png';
}
$src_width = imageSX($src_image); // Width of the original image
$src_height = imageSY($src_image); // Height of the original image
$min_side = min($src_width, $src_height);
/*********** If you need this part uncomment it
$ratio = $min_side / $thumb_width;
$new_width = floor($src_width / $ratio);
$new_height = floor($src_height / $ratio);
**********************************************/
$dst_image = imagecreatetruecolor($thumb_side, $thumb_side);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $thumb_side, $thumb_side, $min_side, $min_side);
switch ($image_extension)
{
case 'jpg':
imagejpeg($dst_image, $thumb_name . '.jpg', 100);
break;
case 'png':
imagepng($dst_image, $thumb_name . '.jpg', 100);
break;
}
imagedestroy($src_image);
imagedestroy($dst_image);
?>
$modwidth3 = 500; //I resize the picture width to smaller as 60px.
$diff3 = $width3 / $modwidth3;
$modheight3 = $height3 / $diff3; //I resize the picture height to smaller.
$left = 1; //getting the left and top coordinate
$top = 1;
$cropwidth = 50; //thumb size
$cropheight = 50;
imagecopyresampled($tn3, $image3, 0, 0, $left, $top, $cropwidth, $cropheight, $modwidth3, $modheight3) ;
$modwidth3 and $modheight3 need to correspond to the width and height of the image you want to crop. Also $top and $left should match the top left coordinate of the area you want to crop. If the original image is 600x500 px and you want to resize and crop to 50x50, you should set $top to 0 and $left to 50 (px). Both $modwidth and $modheight should be set to 500. That keeps the full height of the original image and cuts away 50px from the left hand side and 50px from the right hand side. The remaining 500px is cropped to 50px.
link to a blog article i wrote about how to resize any size image to any arbitrary size. includes options for letterboxing and crop-to-fit.
http://www.spotlesswebdesign.com/blog.php?id=1