I'm using this script to create a watermark on one of client's websites the problem is that one watermark is suitable for one image and unsuitable for another.
Portrait
Landscape
Here is the script:
<?php
// this script creates a watermarked image from an image file - can be a .jpg .gif or .png file
// where watermark.gif is a mostly transparent gif image with the watermark - goes in the same directory asthis script
// where this script is named watermark.php
// call this script with an image tag
// <img src="watermark.php?path=imagepath"> where path is a relative path such as subdirectory/image.jpg
$imagesource = $_GET['path'];
$filetype = substr($imagesource,strlen($imagesource)-4,4);
$filetype = strtolower($filetype);
if($filetype == ".gif") $image = #imagecreatefromgif($imagesource);
if($filetype == ".jpg") $image = #imagecreatefromjpeg($imagesource);
if($filetype == ".png") $image = #imagecreatefrompng($imagesource);
if (!$image) die();
//This bit is the dynamic bit
if(imagesx($image) <=1100){
$watermark = #imagecreatefromgif('watermark_port.gif');
}elseif(imagesx($image) <=1600 && $imagewidth >1100){
$watermark = #imagecreatefromgif('watermark_lans.gif');
}elseif(imagesx($image) >1600){
$watermark = #imagecreatefromgif('watermark_lans.gif');
};
//End of dynamic code
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth,
$watermarkheight);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
However the dynamic watermark doesn't work. What i want is if the image is under 1100px wide then it uses the portrait version and if it is over that to use the landscape version instead.
Any idea would be greatly apprieciated.
Thanks,
David
What your "dynamic part" is doing is basically summed up as:
if something
do A
else if something
do B
else
do B
The middle one is completely redundant.
What you need is just:
$watermark =
imagecreatefromgif("watermark_".(imagesx($image) <= 1100 ? "port" : "lans").".gif");
Related
My Idea is to upload a image file that is combined with a watermark. This code needs to work like this. On a portfolio website, the owner uploads an image he wants to sell throught the CMS i made. But because he wants to sell the image he wants it to come on the site with a watermark.
So my idea, i let him upload the original image, then i get the image through the $_Files() en combine it with a watermark, make it one image again and upload that image.
Now is my question, how do i upload a image created in PHP i tried to convert it to Base64 but with no luck. Here is my code.
Sorry for the bad english!
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$filetype = substr($target_file, -4);
if($filetype == ".gif") $image = #imagecreatefromgif($_FILES["fileToUpload"]["tmp_name"]);
if($filetype == ".jpg") $image = #imagecreatefromjpeg($_FILES["fileToUpload"]["tmp_name"]);
if($filetype == ".png") $image = #imagecreatefrompng($_FILES["fileToUpload"]["tmp_name"]);
if (empty($image)) die();
$watermark = #imagecreatefrompng('watermark.png');
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
file_put_contents($target_file, $image)
Try this:
imagejpeg($image, $target_file);
or imagepng($image, $target_file);
or imagegif($image, $target_file);
I am passing values from the img src like this:
PageA:
<img src="watermark.php?fname=<?php echo $image; ?>" />
then I ge the value on pageB:
$fname = $_GET['fname'];
$watermark_img = $passed_fname;
...
For some reason no image is showing ... I'm I missing something here?
Here is pageB full code:
<?php
$fname = $_GET['fname'];
$main_img = "Porsche_911_996_Carrera_4S.jpg"; // main big photo / picture
//$watermark_img = "watermark.gif"; // use GIF or PNG, JPEG has no tranparency support
$watermark_img = $fname;
$padding = 3; // distance to border in pixels for watermark image
$opacity = 100; // image opacity for transparent watermark
$watermark = imagecreatefromgif($watermark_img); // create watermark
$image = imagecreatefromjpeg($main_img); // create main graphic
if(!$image || !$watermark) die("Error: main image or watermark could not be loaded!");
$watermark_size = getimagesize($watermark_img);
$watermark_width = $watermark_size[0];
$watermark_height = $watermark_size[1];
$image_size = getimagesize($main_img);
$dest_x = $image_size[0] - $watermark_width - $padding;
$dest_y = $image_size[1] - $watermark_height - $padding;
// copy watermark on main image
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $opacity);
// print image to screen
header("content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
Does $image contains some special characters?
Try to use PHP urlencode() function:
<img src="watermark.php?fname=<?php echo urlencode($image); ?>/>
And the, on the second page:
$fname = urldecode($_REQUEST['fname']);
If the value you pass on $fname is just the name, you might need to specify the full path.
$watermark_img = '/PATH_TO_THE_IMAGE/'.$fname;
Try the watermark PHP directly from the address bar, then view source. If there is any output before you set the jpeg header, the browser will be unable to deal with it. You might have something like
Error line 3443234
JPEGIMAGECODE
That first line makes it an invalid image.
I need to help a friend to make his own artistic gallery.
I already have all done, but I need a tool/plugin/script to make him independent from me in uploading his own images. My gallery needs two images: a cropped one of a certain proportion (so i need him to crop by himself in an uploading page) and a thumb one (I want this be done automatically).
Do you know an easy way to do this? What would you do?
Thanks.
Personally i use this in all of my projects - http://www.verot.net/php_class_upload.htm
Works perfectly with upload files and with files that's already on the system.
Can do many things convert, resize and work on uploaded images in many ways, apply effects, add labels, watermarks and reflections and other image editing features.
Easy to work with.
If you're not going to be having heavy traffic to start - look at http://phpthumb.sourceforge.net/ which can create your resized images on the fly.
You need only GD library, function imagecopyresampled will suit you. PHP manual has really good example code for thumbnail creation http://php.net/manual/en/function.imagecopyresampled.php
You will need just to create exceptions for different file formats
function create_jpeg_thumbnail($thumbImageName,$imgSrc,$thumbDirectory,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
$thumbDirectory = trim($thumbDirectory);
$imageSourceExploded = explode('/', $imgSrc);
$imageName = $imageSourceExploded[count($imageSourceExploded)-1];
$imageDirectory = str_replace($imageName, '', $imgSrc);
$filetype = explode('.',$imageName);
$filetype = strtolower($filetype[count($filetype)-1]);
//getting the image dimensions
list($width_orig, $height_orig) = getimagesize($imgSrc);
//$myImage = imagecreatefromjpeg($imgSrc);
if ($filetype == 'jpg') {
$myImage = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
$myImage = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'png') {
$myImage = imagecreatefrompng("$imageDirectory/$imageName");
} else
if ($filetype == 'gif') {
$myImage = imagecreatefromgif("$imageDirectory/$imageName");
}
$ratio_orig = $width_orig/$height_orig;
if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle
$process = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
//$thumbImageName = 'thumb_'.get_random_no().'.jpeg';
$destination = $thumbDirectory=='' ? $thumbImageName : $thumbDirectory."/".$thumbImageName;
imagejpeg($thumb, $destination, 100);
return $thumbImageName;
}
I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?
Thanks!
PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.
In ImageMagick, image resizing is accomplished like this:
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
With GD, you can do it like this:
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
Ok, so below is an Image object that I use in my store. It maintains scale - requires GD
<?php
class Store_Model_Image extends My_Model_Abstract
{
const PATH = STORE_MODEL_IMAGE_PATH;
const URL = "/store-assets/product-images/";
public function get_image_url($width, $height)
{
$old_file = self::PATH . $this->get_filename();
$basename = pathinfo($old_file, PATHINFO_FILENAME);
$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
if(file_exists(self::PATH . $new_name))
{
return self::URL . $new_name;
}
else
{
list($width_orig, $height_orig, $image_type) = #getimagesize($old_file);
$img = FALSE;
// Get the image and create a thumbnail
switch($image_type)
{
case 1:
$img = #imagecreatefromgif($old_file);
break;
case 2:
$img = #imagecreatefromjpeg($old_file);
break;
case 3:
$img = #imagecreatefrompng($old_file);
break;
}
if(!$img)
{
throw new Zend_Exception("ERROR: Could not create image handle from path.");
}
// Build the thumbnail
if($width_orig > $height_orig)
{
$width_ratio = $width / $width_orig;
$new_width = $width;
$new_height = $height_orig * $width_ratio;
}
else
{
$height_ratio = $height / $height_orig;
$new_width = $width_orig * $height_ratio;
$new_height = $height;
}
$new_img = #imagecreatetruecolor($new_width, $new_height);
// Fill the image black
if(!#imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
{
throw new Zend_Exception("ERROR: Could not fill new image");
}
if(!#imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
{
throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
}
// Use a output buffering to load the image into a variable
ob_start();
imagejpeg($new_img, NULL, 100);
$image_contents = ob_get_contents();
ob_end_clean();
// lastly (for the example) we are writing the string to a file
$fh = fopen(self::PATH . $new_name, "a+");
fwrite($fh, $image_contents);
fclose($fh);
return self::URL . $new_name;
}
}
}
I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)
So in the template you pass your image object, and when you need a image thumb,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
you now have a 100x100 thumb, which is saved to the Server for reuse at a later date
gd and imagemagick are two tools that may work for you
http://php.net/manual/en/book.image.php
http://php.net/manual/en/book.imagick.php
Here is something I used to use
class cropImage{
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;
function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {
//Your Image
$this->imgSrc = $image;
//getting the image dimensions
list($width, $height) = getimagesize($this->imgSrc);
//create image from the jpeg
$this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
if($width > $height) $biggestSide = $width; //find biggest length
else $biggestSide = $height;
//The crop size will be half that of the largest side
//$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)
if(!$cropPercent) {
$cropPercent = 1.50;
}
$this->cropWidth = $moduleWidth*$cropPercent;
$this->cropHeight = $moduleHeight*$cropPercent;
//$this->cropWidth = $biggestSide*$cropPercent;
//$this->cropHeight = $biggestSide*$cropPercent;
//getting the top left coordinate
$this->x = ($width-$this->cropWidth)/2;
$this->y = ($height-$this->cropHeight)/2;
}
function createThumb($moduleWidth,$moduleHeight){
$thumbSize = 495; // will create a 250 x 250 thumb
$this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight);
//$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight);
//imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight);
}
function renderImage(){
header('Content-type: image/jpeg');
imagejpeg($this->thumb);
imagedestroy($this->thumb);
}
}
Call it by using
$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).
There a simple to use, open source library called PHP Image Magician that will can help you out.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');
Im having issue when a user uploads and try's to crop a PNG or transparent image( with .gif)
I am getting:
Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: in statusUpFunctions.php on line 100
Warning: imagecreatefromjpeg(): 'images/status/photo/1-6.jpg' is not a valid JPEG file in statusUpFunctions.php on line 100
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in statusUpFunctions.php on line 114
This may be because of my php crop function:
case 'crop':
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
ini_set('memory_limit', '256M');
$jpeg_quality = 90;
$src = "images/status/photo/".$_POST['fname'];
$img_r = imagecreatefromjpeg($src);
if($_POST['fixed'] == 0) {
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
}
else {
$targ_h = $_POST['sizeh'];
$targ_w = $_POST['sizew'];
}
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
$path_thumbs = "images/status/photo";
$filename = $newfilename;
$thumb_path = $path_thumbs . '/' . $filename;
imagejpeg($dst_r,$thumb_path,$jpeg_quality);
}
break;
}
It creates from jpg, cant i make so it creates from gif and png and bmp and so..? and then convert it somehow..
How should this be solved?
The function imagecreatefromjpeg() creates a generic PHP image object from a jpeg image. You can then do whatever you want with the object.
imagecreatefromjpeg() will ONLY create a generic image object FROM a JPEG. If you want to create a generic image object FROM a PNG or GIF, you need to use their respective functions: imagecreatefrompng() and imagecreatefromgif(). One quick way to detect an image's type is by reading its file extension.
Once you have that generic image object, then you can do what you want with it (including using imagecopyresampled()), and then create a jpeg image from it using imagejpeg().
EDIT:
You can use pathinfo() to detect the file's extension:
$filename = pathinfo($_POST['fname']); // Returns an array of file details
$extension = $filename['extension'];
If you are getting the filename from a $_POST value, you need to make sure that you are copying the temporary image file to that filename. I don't see any $_FILES values used in your code (maybe you're doing it in another script?). If not, here's a good tutorial on handling file uploads. It also covers file extensions.
Try This... It will work..
<?php
$image = imagecreatefrompng('photo.png');
$thumb_width = 280;
$thumb_height = 200;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect ){
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}else{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$crop = imagecreatetruecolor($thumb_width,$thumb_height);
imagealphablending($crop, false);
$white = imagecolorallocatealpha($crop, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($crop,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($crop, true);
$userImage = imagecopyresampled($crop, $image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0, $new_width, $new_height,
$width, $height);
header('Content-type: image/png');
imagepng($crop);
?>
It fails to load the image, causing imagecreatefromjpeg() to return false. Make sure that you're trying to open an valid image.
For gif and png files you need to get the image identifier using imagecreatefromgif and imagecreatefrompng
<?php
$image = imagecreatefrompng('myPhoto.png');
$crop = imagecreatetruecolor(50,50);
$userImage = imagecopyresampled($crop, $image, 0, 0, 0, 0, 50, 50, 8, 8);
header('Content-type: image/png');
imagepng($crop);
?>
This will return cropped image.