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.
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);
Actually, Here user can upload any size image to fit into any frame which i have. I want to fit that image into a frame without losing ratio.
Example:
This image is not fitting with my php code.
My code is
list($width, $height) = getimagesize($img1);
$outputImage = imagecreatetruecolor($width, $height);
// set background to white
//$white = imagecolorallocate($outputImage, 255, 255, 255);
//imagefill($outputImage, 0, 0, $white);
list($width1, $height1) = getimagesize($img2);
$info1 = getimagesize($img1);
$info2 = getimagesize($img2);
$extension1 = image_type_to_extension($info1[2]);
$extension2 = image_type_to_extension($info2[2]);
if($extension1=='.jpeg') {
$first = imagecreatefromjpeg($img1);
} else {
$first = imagecreatefrompng($img1);
}
if($extension2=='.jpeg') {
$second = imagecreatefromjpeg($img2);
} else {
$second = imagecreatefrompng($img2);
}
$ratio = $width1 / $height1;
$targetWidth = 300 * $ratio;
//echo $targetWidth;
//imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
imagecopyresampled($outputImage,$first,0,0,0,0, $width, $height, $width, $height);
imagecopyresampled($outputImage,$second,110,75,0,0, $targetWidth, 300, $width1, $height1);
Please help me. Thanks in advance.
to achieve that you must detect the frame image and source image dimensions
re size the source image to fit the frame image dimensions.
note that to avoid ratio problems we will detect if the source image wide image or tall image (landscape or portrait)
if width > height then set the width to the width of frame and calculate the new height based on main ratio
if height > width
set height to frame height and calculate the new width
this is sample implementation code
<?
$src = imagecreatefromjpeg('source.jpg');//source image path
$frame = imagecreatefrompng('frame.png');//frame image
$sourceWidth = imagesx($src); // source image width
$sourceHeight = imagesy($src); // image image height
$frameWidth = imagesx($frame);//get frame width
$frameHeight = imagesy($frame);//get frame height
$NewImage = imagecreatetruecolor($frameWidth,$frameHeight);//the new image
$bg_color = imagecolorallocate ($NewImage, 255, 255, 255);
imagefill($NewImage, 0, 0, $bg_color);//set background to white
if($sourceHeight >= $sourceWidth){
$newHeight=$frameHeight;// set height to frame height
$newWidth=intval($frameWidth*$sourceWidth/$sourceHeight);//calculate the new width
imagecopyresampled($NewImage, $src, intval(($frameWidth-$newWidth)/2),0,0,0,$newWidth, $newHeight, $sourceWidth, $sourceHeight);//insert source image to new image at the center
} else {
$newWidth=$frameWidth;;// set width to frame width
$newHeight=intval($frameHeight*$sourceHeight/$sourceWidth);//calculate the new height
imagecopyresampled($NewImage, $src,0,intval(($frameHeight-$newHeight)/2),0,0,$newWidth, $newHeight,$sourceWidth, $sourceHeight);//insert source image to new image at the center
}
imagecopyresampled($NewImage, $frame, 0,0, 0,0, $frameWidth, $frameHeight, $frameWidth, $frameHeight);//copy frame imageto new image
header("Content-type: image/png");
imagejpeg($NewImage);
?>
hope this would help.
I want to resize 2 types of images (png, gif) with transparent background...
But in png it works well in big size of the original image.
eg. Original file dimension is 150x150
change into 200x200 or exceeding the original size it works well. but in 100x100 it displays
Then the last GIF it doesn't work.
Here my code for png
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
$transparentindex = imagecolorallocatealpha($new_img, 255, 255, 255, 127);
imagefill($new_img, 0, 0, $transparentindex);
imagepng($new_img, $dir);
Here my code for gif
imagegif($new_img, $dir);
I know no PHP, but this seems to do the trick:
#!/usr/local/bin/php -f
<?php
$neww=100;
$newh=100;
// Load original image and get its dimensions
$img = imagecreatefrompng("badge.png");
$w=imagesx($img);
$h=imagesy($img);
// Create output image, and fill with lots of transparency
$out = imagecreatetruecolor($neww,$newh);
imagealphablending($out,false);
$transparentindex = imagecolorallocatealpha($out,0,0,0,127);
imagefill($out,0,0,$transparentindex);
imagesavealpha($out, true);
// Copy original image, reized on top
imagecopyresized($out,$img,0,0,0,0,$neww,$newh,$w,$h);
imagepng($out,"out.png");
?>
Here is a little hack :)
Don't have any other ideas.
It involves a second image (1x1 trasparent gif)
create image
resize
create a transparent background with same size as resized image
use imagecolortransparent() to get the rgb index
imagecopymerge() images
voilĂ
.
$dir = 'http://i.stack.imgur.com/DbhrJ.png';
$max_w = 50;
$max_h = 50;
// get image size
list($src_w, $src_h) = getimagesize($dir);
if ($src_w > $max_w) {
$ratio = $max_w / $src_w;
$max_w = $src_w * $ratio;
}
else if ($src_h > $max_h) {
$ratio = $max_h / $src_h;
$max_h = $src_h * $ratio;
}
// resize image to $max_w and $max_h, and also save alpha
$src = imagecreatefromstring(file_get_contents($dir));
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
imagecopyresampled($new_img, $src, 0, 0, 0, 0, $max_w, $max_h, $src_w, $src_h);
// create a new image with $max_w and $max_h
$maxsize = imagecreatetruecolor($max_w, $max_h);
// add 1x1 gif and resize, then copy over $maxsize
$background = imagecreatefromgif("http://i.imgur.com/atRjCdk.gif"); // transparent 1x1 gif
imagecopyresampled($maxsize, $background, 0, 0, 0, 0, $max_w, $max_h, 1, 1);
// allocate transparency
$transparent = imagecolortransparent($maxsize);
$transparent_index = imagecolorallocate($maxsize, $transparent['red'], $transparent['green'], $transparent['blue']);
imagecolortransparent($maxsize, $transparent_index);
// image copy
imagecopymerge($maxsize, $new_img, 0, 0, 0, 0, $max_w, $max_h, 100);
// save or output
imagegif($maxsize, $path_to_save);
// destroy images
imagedestroy($maxsize);
imagedestroy($new_img);
imagedestroy($background);
imagedestroy($src);
I'm trying to build a function that takes a PHP image resource and places it in the center of a new image of predetermined size. I do not want to scale the image; rather I want to place it as-is in the center of an enlarged "canvas."
$img is a valid image resource - if I return it I receive the correct original (unprocessed) image. $canvas_w and $canvas_h are the width and height of the desired new canvas. It's creating the correct size canvas, but the contents of the file are unexpectedly solid black when I return the desired "corrected" image resource ($newimg).
// what file?
$file = 'smile.jpg';
// load the image
$img = imagecreatefromjpeg($file);
// resize canvas (not the source data)
$newimg = imageCorrect($img, false, 1024, 768);
// insert image
header("Content-Type: image/jpeg");
imagejpeg($newimg);
exit;
function imageCorrect($image, $background = false, $canvas_w, $canvas_h) {
if (!$background) {
$background = imagecolorallocate($image, 255, 255, 255);
}
$img_h = imagesy($image);
$img_w = imagesx($image);
// create new image (canvas) of proper aspect ratio
$img = imagecreatetruecolor($canvas_w, $canvas_h);
// fill the background
imagefill($img, 0, 0, $background);
// offset values (center the original image to new canvas)
$xoffset = ($canvas_w - $img_w) / 2;
$yoffset = ($canvas_h - $img_h) / 2;
// copy
imagecopy($img, $image, $xoffset, $yoffset, $canvas_w, $canvas_h, $img_w, $img_h);
// destroy old image cursor
//imagedestroy($image);
return $img; // returns a black original file area properly sized/filled
//return $image; // works to return the unprocessed file
}
Any hints or obvious errors here? Thanks for any suggestions.
In place of imagecopy(), this seemed to work:
imagecopymerge($img, $image, $xoffset, $yoffset, 0,0, $img_w, $img_h, 100);
here is the website im talking about
http://makeupbyarpi.com/portfolio.php
you'll notice some of the images are smushed width-wise.
the code i used is this:
$width="500";
$height="636";
$img_src = $_FILES['galleryimg']['tmp_name'];
$thumb = "../gallery/".rand(0,100000).".jpg";
//Create image stream
$image = imagecreatefromjpeg($img_src);
//Gather and store the width and height
list($image_width, $image_height) = getimagesize($img_src);
//Resample/resize the image
$tmp_img = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp_img, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//Attempt to save the new thumbnail
if(is_writeable(dirname($thumb))){
imagejpeg($tmp_img, $thumb, 100);
}
//Free memory
imagedestroy($tmp_img);
imagedestroy($image);
the images that get uploaded are huge sometimes 3000px by 2000px and i have php crop it down to 500 x 536 and some landscape based images get smushed. is there a formula i can use to crop it carefully so that the image comes out good?
thanks
You could resize and add a letterbox if required. You simply need to resize the width and then calculate the new height (assuming width to height ratio is same as original) then if the height is not equal to the preferred height you need to draw a black rectangle (cover background) and then centre the image.
You could also do a pillarbox, but then you do the exact same as above except that width becomes height and height becomes width.
Edit: Actually, you resize the one that is the biggest, if width is bigger, you resize that and if height is bigger then you resize that. And depending on which one you resize, your script should either letterbox or pillarbox.
EDIT 2:
<?php
// Define image to resize
$img_src = $_FILES['galleryimg']['tmp_name'];
$thumb = "../gallery/" . rand(0,100000) . ".jpg";
// Define resize width and height
$width = 500;
$height = 636;
// Open image
$img = imagecreatefromjpeg($img_src);
// Store image width and height
list($img_width, $img_height) = getimagesize($img_src);
// Create the new image
$new_img = imagecreatetruecolor($width, $height);
// Calculate stuff and resize image accordingly
if (($width/$img_width) < ($height/$img_height)) {
$new_width = $width;
$new_height = ($width/$img_width) * $img_height;
$new_x = 0;
$new_y = ($height - $new_height) / 2;
} else {
$new_width = ($height/$img_height) * $img_width;
$new_height = $height;
$new_x = ($width - $new_width) / 2;
$new_y = 0;
}
imagecopyresampled($new_img, $img, $new_x, $new_y, 0, 0, $new_width, $new_height, $img_width, $img_height);
// Save thumbnail
if (is_writeable(dirname($thumb))) {
imagejpeg($new_img, $thumb, 100);
}
// Free up resources
imagedestroy($new_img);
imagedestroy($img);
?>
Sorry it took a while, I ran across a small bug in the calculation part which I was unable to fix for like 10 minutes =/ This should work.