Watermark zipped images - php

I currently use the following code to watermark images on-the-fly and display them in a web page:
header('Content-type: image/jpeg');
$stamp = imagecreatefrompng(watermark.png');
$im = imagecreatefromjpeg($filename);
imagecopy($im, $stamp, 10, imagesy($im) - imagesy($stamp) - 10, 0, 0, imagesx($stamp), imagesy($stamp));
imagejpeg($im);
imagedestroy($im);
I also have a lot of images that are stored in zip archives. I currently display them with the following code.
$zip = new ZipArchive();
$opened = $zip->open($zipname, ZIPARCHIVE::CHECKCONS);
if ( $opened === true ){
$content = $zip->getFromName($filename);
header('Content-type: image/jpeg');
echo $content;
};
$zip->close();
I want to watermark them as well but cannot seem to get it to work. As an initial test I tried changing to output of $content from an echo to:
imagejpeg($content);
But that did not work, meaning adding the other watermark code will not work either. Any suggestions as to how to modify the zip code to include the watermark would be greatly appreciated.
I basically do not understand the difference between what is created in $im with imagecreatefromjpeg and what is extracted to $output from the zip archive. I assume that $output contains the raw jpg file data, but have no idea what $im contains.

UPDATE: Answered my own question. All I needed was to add the following after getting $content from the zip:
$im = imagecreatefromstring($content);
I can then apply the watermark exactly as in the first example. Hope that helps others.

Related

PHP: how to use getimgasize() after the image is resized using getimageresized after upload?

using the example given at http://www.php.net/manual/en/function.imagecopyresized.php ... how to get image sizes afterward using getimagesize() function?
CODE:
<?php
if(isset($_FILES['images'])){
//TEST1:
$img = resize_this_image_now($_FILES['images']['tmp_name']);
//TEST2:
$img = resize_this_image_now($_FILES['images']['name']);/// This Drastically failed.
$new_image = getimagesize($img);
var_dump($new_image[0]);// I guessed this should have printed out the WIDTH_OF_THE_IMAGE... but, it prints some NON_READABLE stuffs (why?)
}
// The PHP.NET CODE in a Function
function resize_this_image_now($filename){
// File and new size
// $filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
return imagejpeg($thumb);
}
?>
All I want is to get the Size of the Image.... also, is it possible to do something like:
$_FILES['images']['tmp_name'] = $the_newly_resized_image_returned_from_the_PHP_dot_NET_code'; .... So that the ['images']['tmp_name'] will now have as source this new image??
Any suggestion is highly appreciated...
I decided to spend sometime examining you question. What I found out is that, I don't think you'd need to return the resized image through imagejpeg() the way you did. You might also need to add a imagedestroy(), after you call imagejpeg() in you function, to destroy the temporary memory used.
You need to first fully Upload the Image before resizing it. If you'd like, you could send the image in a temporary storage while you do whatever you want to it so that Php does not have to deal with it in a 'tmp_name' format...Then You can destroy the image later on.
Once the image is fully uploaded, things become easier. The codes might look something like:
if(isset($_FILES['images'])){
//may be some random numbers to accompany it.
$rand = floor((mt_rand()+rand()+mt_rand())/3);
//Send it to the temporary folder you have had to create.
if(move_uploaded_file(
$_FILES['images']['tmp_name'],'temporary_storage/image_'.$rand.'.jpg')){
//Then run the `resize` function from here.
$image_resized = resize_this_image_now('temporary_storage/image_'.$rand.'.jpg');
//Now You can get the size if you wish.
list($width,$height) = getimagesize('temporary_storage/image_'.$rand.'.jpg');
// Out put
echo "W:".$width."<br>H:".$height;
//After you use it as desired, you can now destroy it using unlink or so.
unlink('temporary_storage/image_'.$rand.'.jpg');
}else{
echo "Upload Error goes here";
}
}
Note this answer is produced after several trials and errors... Please use this strategy wisely.
Hope it helps.

Attempting to merge a png over a jpg using PHP

I am trying to merge two images using PHP. One is a jpg that I have pulled in the form of a Facebook URL, the other is a "watermark" logo that is a png that I hope to apply in the bottom right hand corner of the Facebook image before posting the image back to Facebook.
I'm having trouble merging the two images. The function below is passed the url of the Facebook image (which is a jpg) $imagedata = the Facebook image URL. The function is currently returning: Resource id#1. I am hoping to save the merged image to the /uploads/ folder as the same previously randomly generated filename and return it's location from the function.
I have previously referenced this page:
Merge a png ontop of a jpg and retain transparency with php
function createImage($imagedata) {
$upload_dir = ($_SERVER['DOCUMENT_ROOT'] .'/uploads/');
$filename =generateFilename().'.jpg'; //generateFilename() does nothing more than create a random string to use as a unique filename
$filelocation=$upload_dir . $filename;
file_put_contents($filelocation,file_get_contents($imagedata));
$localimage = $filename;
$dest = imagecreatefromjpeg('/uploads/' . $localimage);
$src = imagecreatefrompng('images/overlay.png');
imagecopyresampled($dest, $src, $src2x, $src2y, 0, 0, $src2w, $src2h, $src2w, $src2h);
//header('Content-Type: image/png');
imagejpeg($dest, 'dickshlitz.jpg', 100);
imagedestroy($dest);
imagedestroy($src); }
Any and all help is deeply appreciated. Please ask questions if I have not been clear enough.
Okay, I got this working. My first issue was that I was confused by the output of imagecopyresampled() because I was trying to print it, which isn't what it's designed to do. At the time of posting the initial question I hadn't noticed the .jpg file was being output to my server, so really the code was already doing its job.
However, once I noticed the output and inspected it I noticed it wasn't functioning as expected. This was the fault of my not understanding imagecopyresampled() and passing it variables that hadn't been declared. After much tinkering the working code is below.
$dest = imagecreatefromjpeg('background.jpg');
$src = imagecreatefrompng('watermark.png');
imagesavealpha($src, true);
imagealphablending($src, true);
imagesavealpha($dest, true);
imagealphablending($dest, true);
list($newwidth, $newheight, $type, $attr) = getimagesize('overlay.png');
imagecopyresampled($dest, $src, 200 , 100, 0, 0, $newwidth , $newheight, $newwidth , $newheight);
imagepng($dest, $localimage);
imagedestroy($dest);
imagedestroy($src);
If anyone can make commnent to improve this code I would appreciate it.

Image not rotating

I am trying to rotate image using php imagerotate function but its not working.
GD Library is also on.
i have tried this ,
public function rotate()
{
$targ_w = 240;
$targ_h = 180;
$jpeg_quality = 100;
$degrees = 90;
$src = "/photos/sunset.jpg";
$image = imagecreatefromjpeg($src);
$rotatedImage = imagerotate($image,$degrees,0);
imagejpeg( $rotatedImage,$src,$jpeg_quality);
imagedestroy($rotatedImage);
die();
}
<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
// Output
imagejpeg($rotate);
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>
You're outputing the unchanged $image to file. You should output the rotated one.
imagejpeg( $rotatedImage,$name ,$jpeg_quality);
The second thing - your image is empty. It has only defined width and height but has no content inside it. You defined a $src variable but you don't use it at all.
Maybe you want to replace imagecreatetruecolor with this:
$src = "/photos/sunset.jpg";
$image = imagecreatefromjpeg($src);
You must output the rotated image (pass $rotatedImage instead of $image):
$rotatedImage = imagerotate($image,$degrees,0);
header('Content-type: image/jpeg'); //Header is required to output the image.
imagejpeg($rotatedImage,$name ,$jpeg_quality);
imagedestroy($rotatedImage);
die();
If you are trying to show the image then you need to change that:
header('Content-type: image/jpeg'); //Add jpeg header
imagejpeg( $rotatedImage, NULL, 100); //<-- Notice i remove the $src parameter
If you want to update your jpg file then your code will work, but the user that runs the php file need permissions to write the file. Of course your current image will be overwritten.
And as i said in comments you will need GD version 1.8 or later to work with jpeg files according to php.net

PHP script throwing up garbage in browser when placed inside HTML

So I took the PHP code that creates this page here, and just put it inside of a new .php file, and uploaded that file here.
I just see a ton of garbage characters on the screen. Any ideas?
Here is the full PHP below:
<html>
<head>
<title></title>
</head>
<body>
<?
// gif is more appropriate than jpg for this kind of image
header("Content-type: image/gif");
// both coupon.jpg and Helvetica.ttf must be located in the same directory as
// dynamic.php or these variables must be updated.
$imgname = "./coupon.jpg";
$fontname = "./Helvetica.ttf";
// read image from disk
$im = imagecreatefromjpeg( $imgname )
or die("Source coupon image has been moved or renamed! Expected coupon.jpg");
// variable allocation
$size = 11;
$textheight = 250;
$imwidth = imagesx( $im );
$black = imagecolorallocate( $im, 0,0,0 );
// create the string containing tomorrow's date
$text = "Offer expires " .
date('l\, F j\, Y', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))).".";
// learn the width of the newly allocated string
$bbox = imagettfbbox( $size, 0, $fontname, $text );
$width = $bbox[2] - $bbox[0];
// update, display, and clear from memory the newly modified image
imagettftext($im,$size,0,$imwidth/2 - $width/2,$textheight,$black,$fontname,$text);
imagegif($im);
imagedestroy($im);
?>
</body>
</html>
Update added:
My goal is to have a Google analytics conversion script on the new page / PHP generated image, is that possible?
What did you expect? You're outputting HTML, then after some Content-type: text/plain output (i.e. the HTML), saying Content-type: image/gif
Remove the HTML around the PHP, and just keep the PHP.
Your PHP code creates an image.
This line:
header("Content-type: image/gif");
Allows to modify the HTTP response of the server to tell the browser that you are sending an image. So you do not need all of the HTML code.
You should just keep the PHP code.

Cannot create handle for image after obtaining source code

I am trying to create a small experimental script for obtaining comic strips from web-comic sites using php. The site that I am playing with is Fredo and Pidjin. Here is the code that I have written so far:
<?php
require_once "../shdp/simple_html_dom.php";
$next = "http://www.pidjin.net/2012/08/28/of-my-own/";
$html = file_get_html($next);
$imageList = $html->find('div[class=episode] p img');
for($iii=0; $iii<count($imageList); $iii++){
$storage[$iii] = $imageList[$iii]->src;
}
$img = file_get_contents($storage[0]);
$img = imagecreatefromstring($img);
header("Content-type: image/png");
$something = imagepng($img);
?>
For scraping the html, I am using the Simple HTML DOM parser.
This is what I'm trying to do: Get the src of the image and assign it to a handle. Subsequently find it for all the comic panels on the page and use imagecopy to make one strip that can be saved to the computer. The code, however, is in the preliminary stages and I have not got to the imagecopy part yet.
Problem: While imagepng(...) outputs the file on the browser, I am not able to get a $src handle (so to speak) on the image to use in imagecopy.
Thanks in advance.
How are you trying to get a handle to the image?
$src = imagecreatefrompng($storage[0]);
$dest = imagecreatetruecolor(80, 40);
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
header('Content-Type: image/png');
imagepng($dest);
In case you need to show multiple images try with output buffering:
ob_start();
header('Content-Type: image/png');
imagepng($img1);
header('Content-Type: image/png');
imagepng($img2);
ob_end_flush();

Categories