Having a few teething problems watermarking a photo. It all works fine apart from the watermarked photo's colors become duller than they should be - very noticeable in-fact.
I'm using imagecopyresized to do my watermarking, as this specifically allows me to use PNG-24 watermarks, the others do not. I know the colors are usually OK, as I have just used readfile($url) as a test, and the photos are perfect.
Here is my script:
<?php
// get parent and watermark images & sizes
$image = imagecreatefromjpeg($url);
$imageSize = getimagesize($url);
$watermark = imagecreatefrompng('watermark.png');
$watermark_o_width = imagesx($watermark);
$watermark_o_height = imagesy($watermark);
// calculate new watermark width and position
if ($imageSize[0] > $imageSize[1] || $imageSize[0] == $imageSize[1]) {
$leftPercent = 23;
} else {
$leftPercent = 7;
}
$leftPixels = ($imageSize[0]/100)*$leftPercent;
$newWatermarkWidth = $imageSize[0]-$leftPixels;
$newWatermarkHeight = $watermark_o_height * ($newWatermarkWidth / $watermark_o_width);
// place watermark on parent image, centered and scaled
imagecopyresized(
$image,
$watermark,
$imageSize[0]/2 - $newWatermarkWidth/2,
$imageSize[1]/2 - $newWatermarkHeight/2,
0,
0,
$newWatermarkWidth,
$newWatermarkHeight,
imagesx($watermark),
imagesy($watermark)
);
// print
imagejpeg($image);
// destroy
imagedestroy($image);
imagedestroy($watermark);
?>
How can I stop this from happening? I'm reading about imagecreatetruecolor, does that solve the issue? I'm Googling "imagecreatetruecolor color loss photos" and variations but nobody really talks about this issue. If I do need this function, where would I add that to this script?
This has totally thrown a spanner in the works for me and would love for somebody to tell me where to stick it (not literally).
Here is an example of the color loss. The preview image should be exactly the same colors as the thumbnail. The thumbnails are created using readfile() whereas the previews are created using imagecreatefromjpeg and imagecopresized.
This example code works fine, by using the same characteristics as your images:
Original JPG: dark background; beautiful girl; red dress.
Watermark PNG: transparent background; text; gray color.
<?php
// Path the the requested file (clean up the value if needed)
$path = $url;
// Load image
$image = imagecreatefromjpeg($path);
$w = imagesx($image);
$h = imagesy($image);
// Load watermark
$watermark = imagecreatefrompng('watermark.png');
$ww = imagesx($watermark);
$wh = imagesy($watermark);
// Merge watermark upon the original image (center center)
imagecopy($image, $watermark, (($w/2)-($ww/2)), (($h/2)-($wh/2)), 0, 0, $ww, $wh);
// Output the image to the browser
header('Content-type: image/jpeg');
imagejpeg($image);
// destroy both images
imagedestroy($image);
imagedestroy($watermark);
// kill script
exit();
?>
Left: Output Image | Right: Original Image
Note:
The output image was compressed several times until: Original -> PHP Output -> GIMP -> Here.
After much testing, I came to the conclusion that PHP's GD Image does not support color profiles on the images that are being watermarked. I am now using Imagick and the colors are perfect.
Related
I’m creating an uploader that can upload jpg, giff and png images. Then converts them all too transparent PNG’s and then crops the image based on crop parameters send from client side. The crop can even supply negative axis coordinates, meaning the image is being cropped beyond image dimensions.
To ensure all supported formats can have transparency I first recreate the image into a transparent png, and this is working well.
//GET WIDTH AND HIEGHT OF UPLOADED JPG
list($imageWidth,$imageHeight)= getimagesize($originalDirectory.$file_name);
$image = imagecreatefromjpeg($originalDirectory.$file_name);
//CREATE NEW IMAGE BASED ON WIDTH AND HEIGHT OF SROUCE IMAGE
$bg = imagecreatetruecolor($imageWidth, $imageHeight);
//TRANSPARENCY SETTINGS FOR BOTH DESTINATION AND SOURCE IMAGES
$transparent2 = imagecolorallocatealpha($bg, 0, 0, 0, 127);
$transparent = imagecolorallocatealpha($image, 0,128,255,50); //ONLY TO ENSURE TRANSPARENCY IS WORKING
//SAVE TRANSPARENCY AMD FILL DESTINATION IMAGE
imagealphablending( $bg, false );
imagesavealpha($bg, true);
imagefill($bg, 0, 0, $transparent2);
//SAVE TRANSPARENCY AMD FILL SOURCE IMAGE
imagealphablending( $image, false );
imagesavealpha($image, true);
imagefill($image, 0, 0, $transparent); //ONLY TO ENSURE TRANSPARENCY IS WORKING
//CREATE AND SAVE AS PNG FILE WITH TRANSPARENCY
imagecopy($bg, $image, 0, 0, 0, 0, $imageWidth,$imageHeight);
header('Content-type: image/png');
imagepng($bg, $originalDirectory.$jpgFile);
imagedestroy($bg);
After the new png is created I use it to then only crop the image according to the parameters passed through from the client side scripting.
//GET NEWLY CREATED PNG
$src = imagecreatefrompng($originalSRC);
// NOT SURE IF NECESSARY BUT HAS NO EFFECT ON FINAL RESULT REGGARDLESS OF ANY SETTINGS DONE
imagealphablending( $image, false );
imagesavealpha($image, true);
//DEFINE DESTINATION CROPPED FILE
$thumbHighFilename = $thumbHighDirectory.'test.png';
//CREATE NEW IMAGE BASED ON FINAL CROP SIZE
$tmp = imagecreatetruecolor($cropWidth, $cropHeight);
//ENSURE DESTINATION HAS TRANSPARENT BACKGROUND
$transparent2 = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagefill($tmp, 0, 0, $transparent2);
/* -------------------------------------------------
PROBLEM HERE
When I try to merge the two with the crop paramaters
send from client side. All transparencies work, except
where crop X and Y axis exceeds source image paramaters.
Currently 50px offset on destination image is to verify
transparency works.
The source coordinates are based on image not crop area.
Tried with both imagecopyresized & imagecopyresampled
-------------------------------------------------*/
imagecopyresized($tmp, $src, -50,-50, $xAxis,$yAxis,$cropWidth, $cropHeight, $pW, $pH);
//SAVE FINAL IMAGE
header('Content-type: image/png');
imagepng($tmp, $thumbHighFilename);
imagedestroy($tmp);
This is where the source and destination images still has there transparency; however the negative coordinates creates a black background around the source image. How can I get that to be transparent?
While I found a lot about transparencies, nothing has been a proper solution. For example imagefill afterwards will not work as source could use 100% black around the edges and will make that also transparent then, which it shouldn’t.
CLIENT SIDE CROP EXAMPLE WITH INDICATIONS
CURRENT FINAL IMAGE RESULT WITH ADDED INDICATIONS
From what I could find it seems that there is no way for the GD imagecopyresized and imagecopyresampled to inherit the default backgrounds of the images it is cropping. Thus it keeps adding the default black background to the source image.
The biggest problem I’ve had was actually the crop container being responsive, thus very difficult to determine crop parameters.
To get around the problem I asked my frontend developer to send me more parameters from the crop. Below are all parameters now being passed to php, and the variables in php that are linked to the parameters received:
$xAxisCropper & $yAxisCropper – The variables get the X and Y
coordinates of the container not the image being cropped.
$pW & $pH – Defines the width and height of the crop box.
$containerWidth & $containerheight – As the container is responsive
getting the height and width helps understand what size the
coordinates where calculated on.
$imResizeHeight & $imResizeWidth – Since the images in the container
are always set to be contained within the container, it was important
to get the width and height into which the image is being resized by
the CSS. Giving understanding of what is happening with the image
within the responsive container.
$originalWidth & $originalHeight – Defines the original size of the
image and could either be passed to php or retrieved from the
original image uploaded to the server.
With these parameters I could now recreate the container with the image in the centre, and crop the newly created image. Before I crop it’s important to get the right scaling of the image for the crop, in order to ensure the best quality image is cropped and not compressed before cropping.
To do this I started by determining if the image in the container is being scaled up or down within the container. If scaled up image needs to be scaled to container size, if scaled down the container needs to be increased to have the image fit in the container. Below is the code that currently determines this, and changes the necessary parameters accordingly:
//IF CSS CONTAIN RESIZES HEIGHT EQUAL TO CROP CONTAINER HEIGHT
if($imResizeHeight == $containerheight){
//IF IMAGE SIZE WAS INCREASED
if($imResizeHeight>$originalHeight){
//DEFINE NEW IMAGE SIZE TO SCALE TO CONTAINER
$new_height = $imResizeHeight;
$new_width = $originalWidth * ($new_height / $originalHeight);
$scale = 'image'; //DEFINE WHAT IS BEING INCREASED
//ESLSE INCREASE CONTAINER TO IMAGE HEIGHT DIMENSIONS
}else{
//RECALCULATE WIDTH & HEIGHT OF CONTAINER
$newContainerWidth = $containerWidth * ($originalHeight / $containerheight);
$newContainerheight = $originalHeight;
$scale = 'container'; //DEFINE WHAT IS BEING INCREASED
}
//IF CSS CONTAIN RESIZES WIDTH EQUAL TO CROP CONTAINER WIDTH
}elseif($imResizeWidth == $containerWidth) {
//IF IMAGE SIZE WAS INCREASED
if($imResizeWidth>$originalWidth){
//DEFINE NEW IMAGE SIZE TO SCALE TO CONTAINER
$new_width = $imResizeWidth;
$new_height = $originalHeight * ($new_width / $originalWidth);
$scale = 'image'; //DEFINE WHAT IS BEING INCREASED
//ESLSE INCREASE CONTAINER TO IMAGE WIDTH DIMENSIONS
}else{
//RECALCULATE WIDTH & HEIGHT OF CONTAINER
$newContainerheight = $containerheight * ($originalWidth / $containerWidth);
$newContainerWidth = $originalWidth;
$scale = 'container'; //DEFINE WHAT IS BEING INCREASED
}
}
//IF IMAGE WAS INCREASED
if($scale=='image'){
//SCALE IMAGE
$src = imagescale ( $src , $new_width , $new_height, IMG_BILINEAR_FIXED);
imagepng($src,$originalSRC,0);
//ADD CHANGES TO VARIABLES USED IN CROP
$pH = $pH * ($new_height / $originalHeight);
$pW = max(0, round($pW * ($new_width / $originalWidth)));
$originalWidth = $new_width;
$originalHeight = $new_height;
$newContainerWidth = $containerWidth;
$newContainerheight = $containerheight;
//ELSE CONTAINER WAS INCREASED
}else {
//RECALCULATE COORDINATES OF CONTAINER
$yAxisCropper = max(0, round($yAxisCropper * ($newContainerheight / $containerheight)));
$xAxisCropper = max(0, round($xAxisCropper * ($newContainerWidth / $containerWidth)));
}
Once the parameters have been redefined according to the scaling, I then create the transparent background according to the container size and add the image in the centre. Thus creating a proper version of the crop container as an image, below the code for creating the new image:
//CALCULATE CENTRE OF NEW CONTAINER
$centreX = max(0, round(($newContainerWidth-$originalWidth)/2));
$centreY = max(0, round(($newContainerheight-$originalHeight)/2));
//CREATE NEW IMAGE BASED ON WIDTH AND HEIGHT OF SROUCE IMAGE
$bg = imagecreatetruecolor($newContainerWidth, $newContainerheight);
//SAVE TRANSPARENCY AMD FILL DESTINATION IMAGE
$transparent = imagecolorallocatealpha($bg, 0,0,0,127);
imagealphablending( $bg, false);
imagesavealpha($bg, true);
imagefill($bg, 0, 0, $transparent);
//CREATE AND SAVE AS PNG FILE WITH TRANSPARENCY
imagecopy($bg, $src, $centreX, $centreY, 0, 0, $originalWidth,$originalHeight);
header('Content-type: image/png');
imagepng($bg, $originalSRC, 0);
imagedestroy($bg);
The result till thus far:
It is only at this point that I send the new image to be cropped according to the specified width and height. Code below:
$src = imagecreatefrompng($originalSRC);
$thumbHighFilename = $thumbHighDirectory.$new_image;
$tmp = imagecreatetruecolor($cropWidth, $cropHeight);
$transparent2 = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagefill($tmp, 0, 0, $transparent2);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $src, 0,0, $xAxisCropper,$yAxisCropper,$cropWidth, $cropHeight, $pW, $pH);
header('Content-type: image/png');
imagepng($tmp, $thumbHighFilename, 2);
Final result cropped 400x300
This has been the only way so far that I’ve managed to solve the problem. Code could probably still be optimised, but if someone has a more optimal solution please share.
I also wish to thank my frontend developer Salem for helping me to solve this irritating issue.
I also did have this annoying black Background Problem with png Files and the imagecropauto Function.
After "some" Tests, i have found a Solution as it seems. At least it works for me.
Here is my mofified Code:
$im=imagecreatefrompng("yourpicture.png");
$cropped=imagecropauto($im, IMG_CROP_SIDES);
imagesavealpha($cropped,true);
if($cropped !==false) {
imagedestroy($im);
$im=$cropped;
}
imagepng($im, "yourpicturecropped.png");
imagedestroy($im);
I'm working on a website which I didn't originally create/develop.
Users can upload an image and when they do that, there's a function that creates a duplicate of that image with a watermark.
But the copy with the watermark is of low quality and also its size is much smaller than the original image
Without watermark
With watermark
function watermark( $path ){
$watermark = imagecreatefrompng('files/watermark.png');
$wmsize = getimagesize('files/watermark.png');
$image = imagecreatefromjpeg($path);
$size = getimagesize($path);
$dest_x = (8);
$dest_y = ($size[1] - 35 );
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $wmsize[0], $wmsize[1]);
ob_start();
imagejpeg($image);
$img2 = ob_get_contents();
ob_end_clean();
imagedestroy($image);
return $img2 ;
}
The image quality is decreased because of JPEG compression.
Every time you save image as JPEG you decrease its quality because JPEG uses lossy compression. You can minimize the loss by setting the compress quality to 100%, but if you would like to perform lossless compression it is not possible for JPEG and you must look for another image format, e.g. TIFF.
I'm trying to redesign my site so that my original square, tile-based rendering of images can be more of a cutout of the image... to get rid of that grid pattern.
Here's how it looked originally...
Here's a rough mock-up of what I'm going for:
So I resaved an image thumbnail with a transparent background... I just want the dog to show, and the square is transparent which will show the site's background underneath.
Yet when I render it on the page, it has this black background.
I've checked my CSS to see if there is some sort of img class, or class for the rendered comics... or even the bootstrap to see where there may be a background-color being assigned to black (and also searched for hex code 000000), but didn't find one...
Do you know why this may be happening?
Thanks!
EDIT: I've just noticed something...
My logo at the top renders with a transparent background... and the element is a png file... therefore, its MIME type is image/png.
I'm using a thumbnailing script to make the thumbnails smaller, but now the element is of thumber.php, which puts it as MIME type image/jpeg.
So I guess it's my thumbnailing script that changing the MIME type.
So I checked it, and it's creating the file as a jpeg
//imagejpeg outputs the image
imagejpeg($img);
Is there a way to change it so that the resampled image is output as a png?
Thumbnailing script:
<?php
#Appreciation goes to digifuzz (http://www.digifuzz.net) for help on this
$image_file = $_GET['img']; //takes in full path of image
$MAX_WIDTH = $_GET['mw'];
$MAX_HEIGHT = $_GET['mh'];
global $img;
//Check for image
if(!$image_file || $image_file == "") {
die("NO FILE.");
}
//If no max width, set one
if(!$MAX_WIDTH || $MAX_WIDTH == "") {
$MAX_WIDTH="100";
}
//if no max height, set one
if(!$MAX_HEIGHT || $MAX_HEIGHT == "") {
$MAX_HEIGHT = "100";
}
$img = null;
//create image file from 'img' parameter string
$img = imagecreatefrompng($image_file);
//if image successfully loaded...
if($img) {
//get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
//takes min value of these two
$scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);
//if desired new image size is less than original, output new image
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($img);
//replace actual image with new image
$img = $tmp_img;
}
}
//set the content type header
header("Content-type: image/png");
//imagejpeg outputs the image
imagealphablending($img, false);
imagesavealpha($img, true);
imagepng($img);
imagedestroy($img);
?>
You will need to make some changes in the image generator and see if that works out for you.
The crucial changes are within the setting of the header and the method of image generation. You will be looking for these following two
header('Content-Type: image/jpeg');
change to:
header('Content-Type: image/png');
imagejpeg($im);
change to:
imagepng($im)
When dealing with png images with an alpha channel you should take a few extra steps.
Before spitting it out with imagepng(), these lines will need to be added.
imagealphablending($img, false);
imagesavealpha($img, true);
This information can be found on php.net
Edit:
Try with these alterations to this code:
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagealphablending($tmp_img,true); // add this line
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$img = $tmp_img;
// remove line here
}
}
header("Content-type: image/png");
imagesavealpha($img, true);
imagepng($img);
imagedestroy($img);
imagedestroy($tmp_img); // add this line here
Basically you create new layers and put these together. For each layer you will need to set the alpha blending. I was successful in creating alpha images. Let me know what your findings are .. :-) ..
My photo sizes vary, they are either landscape, portrait or square, and I need to make a watermark the best fit for each photo - so I need to resize just the width of the watermark (without Imagick), as it's a long rectangle shape, so height doesn't matter.
I found the PHP function, imagecopyresized, but I'll be honest, I can't work out what parameters are needed for my situation, even after looking at PHP documentation! I'm also not sure if after using imagecopyresized, the rest of my function will work where it gets the watermark width and height.
Can somebody help me get over the finish line. This is how far I got, all it needs is the right parameters added to the imagecopyresized part:
<?php
header('content-type: image/jpeg');
$image = imagecreatefromjpeg('https://.....jpg');
$imageSize = getimagesize('https://.....jpg');
$newWatermarkWidth = $imageSize[0]-50; // width of image minus 50px
$watermark = imagecreatefrompng('watermark.png');
// resize watermark to newWatermarkWidth here with imagecopyresize
$watermark = imagecopyresized(?,?,?,?);
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$dest_x = ($imageSize[0]/2) - ($watermark_width/2) ;
$dest_y = ($imageSize[1]/2) - ($watermark_height/2);
imagecopy($image, $watermark, round($dest_x,0), round($dest_y,0), 0, 0, $watermark_width, $watermark_height);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
THIS IS WHAT I ENDED WITH & WORKS PERFECTLY
A script that adjusts the width of a watermark to fit across the whole parent image, centered and proportional.
<?php
header('content-type: image/jpeg');
$image = imagecreatefromjpeg('http://mydomain.com/myPhoto.jpg');
$imageSize = getimagesize('http://mydomain.com/myPhoto.jpg');
$watermark = imagecreatefrompng('http://mydomain.com/myWatermark.png');
$watermark_o_width = imagesx($watermark);
$watermark_o_height = imagesy($watermark);
$newWatermarkWidth = $imageSize[0]-20;
$newWatermarkHeight = $watermark_o_height * $newWatermarkWidth / $watermark_o_width;
imagecopyresized($image, $watermark, $imageSize[0]/2 - $newWatermarkWidth/2, $imageSize[1]/2 - $newWatermarkHeight/2, 0, 0, $newWatermarkWidth, $newWatermarkHeight, imagesx($watermark), imagesy($watermark));
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
This resizes the watermark and copies directly to the image.
You don't need the existing imagecopy line anymore.
$success = imagecopyresized($image, // Destination image
$watermark, // Source image
$imageSize[0]/2 - $newWatermarkWidth/2, // Destination X
$imageSize[1]/2 - imagesy($watermark)/2, // Destination Y
0, // Source X
0, // Source Y
$newWatermarkWidth, // Destination W
imagesy($watermark), // Destination H
imagesx($watermark), // Source W
imagesy($watermark)); // Source H
I have a PHP script to re size image file as below;
$file = "test.bmp";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$thumbname = "thumb/".$file_name.".".$ext;
$maxh = 200;
$maxw = 200;
$quality = 100;
list($width,$height)=getimagesize($file);
$src = imagecreatefromwbmp($file);
$tmp = imagecreatetruecolor($maxw,$maxh);
imagecopyresampled($tmp,$src,0,0,0,0,200,200,$width,$height);
imagejpeg($tmp,$thumbname,$quality);
imagedestroy($tmp);
The script is suppose to resize a Windows bitmap image to 200x200 thumbnail. But instead, I am getting a black 200x200 image. I am using PHP with Apache in Windows PC. How can I fix this?
.bmp and wbmp are VERY, VERY different file types.
Note the content-type headers:
Content-Type: image/x-xbitmap
Content-Type: image/vnd.wap.wbmp
Calling imagecreatefromwbmp($file) where $file is a .bmp will fail every time.
See this thread for info on how to load a .bmp file. It's not pretty.
As pointed out in PHP imagecopyresampled() docs:
Note:
There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
To see if it's the case you can use imageistruecolor() and copy the contents to a new truecolor image before "copyresampling" it:
if( !imageistruecolor($src) ){
$newim = imagecreatetruecolor( $width, $height );
imagecopy( $newim, $src, 0, 0, 0, 0, $width, $height );
imagedestroy($src);
$src = $newim;
}
There is a new opensource project on Github that allows reading and saving of BMP files (and other file formats) in PHP.
The project is called PHP Image Magician.
<?php
//Create New 'Thumbnail' Image
$newImageWidth = 200;
$newImageHeight = 200;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
$newImageFile = 'output.jpg';
$newImageQuality = 100;
//Load old Image(bmp, jpg, gif, png, etc)
$oldImageFile = "test.jpg";
//Specific function
$oldImage = imagecreatefromjpeg($oldImageFile);
//Non-Specific function
//$oldImageContent = file_get_contents($oldImageFile);
//$oldImage = imagecreatefromstring($oldImageContent);
//Get old Image's details
$oldImageWidth = imagesx($oldImage);
$oldImageHeight = imagesy($oldImage);
//Copy to new Image
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $oldImageWidth, $oldImageHeight);
//Output to file
imagejpeg($newImage, $newImageFile, $newImageQuality);