PHP script throwing up garbage in browser when placed inside HTML - php

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.

Related

Watermark zipped images

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.

Multiple Images and HTML in one File using GD Library

Good day everyone.
Long story short, I'm trying to make an online card game much like urban rivals.
To do so, I'm using mainly PHP and SQL.
Right now, I'm trying to generate the png file of a card based on a database.
I've already managed to merge images with alpha channel, to add text to an image, but my real problem is : I cannot seem to be able to output this image along with other and the basic layout of a HTML document. Here is my test code :
<?php
include 'phpGDtools.php';
$image1path = 'monstercard.png';
$image2path = 'monsterimage.png';
$xdim = 220;
$ydim = 301;
//$image = mergeTwoPNGAndReturn($image1path, $image2path, $xdim, $ydim);
mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim);
echo('Hello !');
?>
Sorry for the bad formatting, I haven't been able to make it better :/
Here is my function in phpGDTools.php:
function mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim)
{
//TEST FUNCTION
//Both paths to the images, x and y dimensions of the image you're about to fuse.
$final_img = imagecreate($xdim, $ydim);
//Step 1 : Create the objects from the PNGs
$image_1 = imagecreatefrompng($image1path);
$image_2 = imagecreatefrompng($image2path);
//Step 1.2 : Allow transparency of bases.
imagealphablending($image_1, true);
imagesavealpha($image_1, true);
imagealphablending($image_2, true);
imagesavealpha($image_2, true);
//Step 2 : Merge the images into one.
imagecopy($image_1, $image_2, 0, 0, 0, 0, $xdim, $ydim);
imagecopy($final_img, $image_1, 0, 0, 0, 0, $xdim, $ydim);
//Step 3 : Allow transparency of final image.
imagealphablending($final_img, true);
imagesavealpha($final_img, true);
//Step 4 : Output image to browser.
header('Content-Type: image/png;');
imagepng($image_1);
}
This outputs very well the image, as intended, but the text "Hello !" is nowhere to be found.
Also, please ignore the part about "$final_image" it's just for testing.
You may have noticed I commented this line :
//$image = mergeTwoPNGAndReturn($image1path, $image2path, $xdim, $ydim);
This is the function I want to use : hopefully, my goal would be to include this php file into an html page, and then being able to print the image object between two tags.
Technically, I could save it as afile and then output the file, but that would be extremely inefficient considering my project.
Thank you for helping me out.
~Jules Courtois
You're setting the content type to an image, so anything you send back will be interpreted as an image. When you're echoing HTML you're adding to the image data which is resulting in the browser not being able to read the image.
You need to create a HTML page then reference images within the HTML file with a or tag with the src to the URL of the image or you can base64 an image to use it inline.
You could replace
imagepng($image_1);
with
ob_start();
imagejpeg($image_1);
$image_data = ob_get_contents ();
ob_end_clean ();
$image_data_base64 = base64_encode($image_data);
echo '<img src="data:image/png;base64,' . $image_data_base64 . '" />';
You should avoid processing images on the fly and try to store them but this should achieve what you asked in the question.
It looks like you are trying to output image data and html data from the same php script.
You call the function
mergeTwoPNGAndOutputInBrowser();
which outputs the image header to the browser.
And then you
echo('Hello !');
Where 'hello' is text data and not image data... So its not displayed in the image.
You could do something like this.
<?php
include 'phpGDtools.php';
$image1path = 'monstercard.png';
$image2path = 'monsterimage.png';
$xdim = 220;
$ydim = 301;
if(isset($_GET['display_image'])){
//Output image data
mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim);
}
else{
//Output page data
echo 'Hello !';
echo "<img src=\"?display_image\">";
}
?>
The Text is not displaying since you have set the header
header('Content-Type: image/png;');
Why don't you use the imagestring() of the same PHP GD Library. It let's you write text on the image.
Here's a cool example. You can embed this same code to your mergeTwoPNGAndOutputInBrowser() function.
<?php
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Source

My captcha image is not being loaded. There is internal server error 505

I have a php file for captcha. But image is not there in web page. I cant find out what is the prob. Please help me. Here is my code.
<?php
ob_start();
session_start();
// Set the content-type
header('Content-Type: image/jpeg');
mimetypes.add_type('application/font-ttf', '.ttf', True)
// Create the image
$im = imagecreatefromjpeg('bg.jpg');
// Create some colors
$R = rand(0,100);
$G = rand(0,100);
$B = rand(0,100);
$cc = imagecolorallocate($im, $R, $G, $B);
// The text to draw
$text = rand(100,10000);
$_SESSION['text'] = $text;
// Replace path by your own font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, rand(40,45), rand(0,1), rand(10,70), rand(38,50), $cc, $font, $text);
$NumberOfLines=15;
imagecolorallocate($im, 15, 142, 210);
$cc=0;
while($cc < $NumberOfLines){
// set random color:::
//assign random rgb values
$c1 = mt_rand(50,200); //r(ed)
$c2 = mt_rand(50,200); //g(reen)
$c3 = mt_rand(50,200); //b(lue)
//test if we have used up palette
if(imagecolorstotal($im)>=255) {
//palette used up; pick closest assigned color
$color = imagecolorclosest($im, $c1, $c2, $c3);
} else {
//palette NOT used up; assign new color
$color = imagecolorallocate($im, $c1, $c2, $c3);
}
// done...
$startH =rand(3,200);
$startTOP = rand(0,8);
$stopH=rand(3,200);
$stopTOP =50;
imageline($im, $startH, $startTOP, $stopH, $stopTOP, $color);
$cc++;
}
// Using imagepng() results in clearer text compared with imagejpeg()
imagejpeg($im);
imagedestroy($im);
?>
Name of this script file is img.php And it is set as src of img
tag like
img src='img.php'
Here arial.ttf file is in the same folder where this php file resides. Please help me for this. This captcha image is not being loaded.
First remove the ob_start() command. It does not make much sense (at least to me).
Then uncomment the header(..) line so that you see error messages in the browser.
I had to do the following things to get the code up and running:
I removed the mimetypes line (is this PHP at all? If yes, a semicolon is missing)
the script did not find the font - I had to use absolute path and set the permissions right
When you are done with debugging and see fancy chars in your browser window, add the header(..) line again.

PHP Overlay GIF on JPEG

At the moment I am generating a barcode using Shay Anderson's class (http://www.shayanderson.com/php/php-barcode-generator-class-code-39.htm) and I am able to successfully display the generated barcode in the browser as follows:
$bc = new PrintBarcode('DARP CODE');
$bc->drawVoucher();
$src = $bc->getVoucher();
// Output and free from memory
header('Content-Type: image/jpeg');
imagejpeg($src);
but now I am trying to modify my script to overlay the barcode on top of another image to create a voucher but I can't seem to get it to work, I just get the broken image icon in Chrome and the following warning in the console:
Resource interpreted as Document but transferred with MIME type image/jpeg
$bc = new PrintBarcode('DARP CODE');
$bc->drawVoucher();
$src = $bc->getVoucher();
header('Content-Type: image/jpeg');
// create actual voucher with barcode overlayed on voucher background
$bg = imagecreatefromjpeg('images/voucher.jpg');
imagecopymerge($bg, $src, 0, 0, 0, 0, imagesx($bg), imagesy($bg), 75);
imagejpeg($bg, null, 100);
imagedestroy($bg);
Error reporting is on and I'm getting no wanrings, notices or fatal errors. Any help appreciated.
The only thing I can think of is that from the docs of the barcode class, it generates the barcode as a gif so not sure if I am missing a few steps.
Turns out the problem was to do with the image I was using as the basis of the merge wasn't quite right so I re-converted it from a png to jpg properly (first time I downloaded the png I simply did a save as all files to jpeg) using photoshop and it was fine, to clarify, here's the code:
$bc = new PrintBarcode('DARP CODE');
$bc->drawVoucher();
$src = $bc->getVoucher();
header('Content-Type: image/jpeg');
$bg = imagecreatefromjpeg('images/voucher.jpg');
imagecopymerge($bg, $src, 40, 380, 0, 0, imagesx($bg), imagesy($bg), 100);
imagejpeg($bg, null, 100);
imagedestroy($src);
imagedestroy($bg);

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