I have a page with a bunch of animated gifs and I would like to use PHP to either freeze them on page load or convert each one to jpg/png. I came across this http://php.net/manual/en/function.imagecreatefromgif.php but I'm not too familiar with PHP. Any help?
Here is the code to convert animated gif to jpg. Taken from This comment on the PHP manual entry
<?php
//This function gif2jpeg take three parameter as argument. two argument are optional
//first will take the gif file name. second for file name to save the converted file. third argument is an color array
//EXAMPLE:
$gifName = $_GET['gif_name']; //ABSOLUTE PATH OF THE IMAGE (according to its location)
$c['red']=255;
$c['green']=0;
$c['blue']=0;
echo gif2jpeg($gifName, '', $c);
function gif2jpeg($p_fl, $p_new_fl='', $bgcolor=false){
list($wd, $ht, $tp, $at)=getimagesize($p_fl);
$img_src=imagecreatefromgif($p_fl);
$img_dst=imagecreatetruecolor($wd,$ht);
$clr['red']=255;
$clr['green']=255;
$clr['blue']=255;
if(is_array($bgcolor)) $clr=$bgcolor;
$kek=imagecolorallocate($img_dst,
$clr['red'],$clr['green'],$clr['blue']);
imagefill($img_dst,0,0,$kek);
imagecopyresampled($img_dst, $img_src, 0, 0,
0, 0, $wd, $ht, $wd, $ht);
$draw=true;
if(strlen($p_new_fl)>0){
if($hnd=fopen($p_new_fl,'w')){
$draw=false;
fclose($hnd);
}
}
if(true==$draw){
header("Content-type: image/jpeg");
imagejpeg($img_dst);
}else imagejpeg($img_dst, $p_new_fl);
imagedestroy($img_dst);
imagedestroy($img_src);
}
?>
How to use:
Add the above code into a php file 'convertGifToJpeg.php'
Add an <img tag. <img src="http://apllicationdomainpath/convertGifToJpeg.php?gif_name=/images/animated_gif.gif" width="200" height="200" />
Make sure have given correct name/path for both the gif image and php file.
Related
So i am trying to create a compass to show wind direction.
Function rotate($angle) {
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $angle, 0);
return $compass;
}
That will be displayed using some html that i am echoing. The variable angle is being passed from a database. The html on the php script looks like this:
<img src='".rotate($row['wind_dir'])."'/>
The image never displays, and clearly the browser does not know where it is.
When i view the html in my browser, the above line shows as
<img src="Resource id #4"/>
and when i click on it, it navigates to a 404.
What am i doing wrong? Have i forgotten a line in the image rotation function?
EDIT:
Having tried some of the responses below, i get an image, but it only shows as a black box!
EDIT2:
Well after much fiddling, it turns out all that was needed was to the third value of imagerotate() to -1 as follows:
$original = imagecreatefrompng("img/goog.png");
$compass = imagerotate($original, $angle, -1);
imagealphablending($compass, true);
imagesavealpha($compass, true);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
I posted a comment about using CSS or JS rotation instead but since then I've had a better idea.
The compass is always going to be Arrow.png in one of 360 positions.
Use a batch process in Photoshop or PHP to create 360 versions. One for each degree. Then you can just call Arrow_120.png for example for 120 degrees. You remove the issue with your existing code of creating images on the fly while avoiding compatibility issues with CSS / JS.
You have to execute the function and send header: try like below, say our php file name is rotate.php :
rotate.php
function rotate($angle) {
$original = imagecreatefrompng("test.png");
$compass = imagerotate($original, $angle, 0);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
}
if(isset($_GET['angle'])){
rotate($_GET['angle']);
}
THen in your html you can call the web resource i.e you php file as:
<img src="url_to_rotate.php?angle=90" />
Also remember to sanitize the GET input before executing it.
The displayed image should be a image file. To achieve this you should use imagejpeg();
So basically you should have 2 php files:
1: Creates the image file using your code and imagejpeg();
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
header('Content-Type: image/jpeg');
imagejpeg($compass);
?>
2: The php file that displays the image.
<img src='image.php?angle=".$row['wind_dir']."'/>
if you want just one file you could do the following:
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
ob_start();
imagepng($compass);
$stringdata = ob_get_contents();
ob_end_clean();
$imageData = base64_encode($stringdata);
$src = 'data: image/png;base64,'.$imageData;
echo '<img src="',$src,'">';
?>
I'm trying to use the WideImage plugin and loading an image into it, resizing it, and then outputting it in the following form:
<img class="image" src="image.jpg" />
I have this so far:
<?php
$image = WideImage::load('image.jpg');
$resizedImage = $image->resize(150, 150, 'outside')->crop('center', 'middle', 150, 150);
?>
How can I output the resized image so that it's in the form above? Help!
Resize
You can resize images by passing a few parameters to the resize() method. The first two are the new dimensions of the image, and can be smart coordinate values. If one dimension isn’t specified (or null is given), it’s calculated from the ratio of the other dimension.
Resize an image into a 400×300 box. By default, resizing keeps the original image’s aspect ratio and the resulting image fits the given dimensions from the inside.
$resized = $image->resize(400, 300);
This is equal to passing ‘inside’ as $fit value.
$resized = $image->resize(400, 300, 'inside');
Resize an image to fit a 400×300 box from the outside by passing ‘outside’ to $fit parameter. This means that the image will be at least as big as 400×300, and aspect ratio will be kept.
$resized = $image->resize(400, 300, 'outside');
Resize an image to exactly fit a 400×300 box by passing ‘fill’ as the value of $fit parameter. The image will be stretched as necessary, aspect ratio may not be kept.
$resized = $image->resize(400, 300, 'fill');
The fourth parameter ($scale) determines when to scale an image. Possible values include any (default), down and up:
down – resize if image is larger than the new dimensions
up – resize if image is smaller than the new dimensions
any – resize regardless of the image size
There are two aliases for the resize method: resizeUp and resizeDown. These two are equal to calling resize() with $scale = ‘up’ and $scale = ‘down’ respectively.
$resized = $image->resize(350, 500, 'inside', 'down');
// is equal to
$resized = $image->resizeDown(350, 500, 'inside');
in your HTML add
<img src= "<?= $resized ?>"> – Moises Zaragoza just now edit
The problem is that the browser attempts to read the image as if it was text, more specifically an html document.
To solve it I would create a new php script for the image processing, let's say image.php, with a function taking the image path and also the parameters of the modification.
In the end just show the image as you did before, just be sure to change the header of the content to something like:
header('Content-type: image/jpg');
or
header('Content-type: image/png');
With that the browser will know how to interpret the data received.
First you have to save the resized image as a file.
In you php put:
<?php
$image = WideImage::load('image.jpg');
$resizedImage = $image->resize(150, 150, 'outside')->crop('center', 'middle', 150, 150);
$resizedImage ->saveToFile('resized_image.jpg');
?>
Then make your image reference the new file:
<img class="image" src="resized_image.jpg" />
I am a student taking a php course and I have been assigned to create a function that creates a square based on a given set of parameters and prints it, but I must use an include statement to print all of the squares.
My Function looks like this :
function squareFunction ($size, $r, $g, $b, $backR, $backG, $backB, $posX, $posY, $length, $height) {
//create an empty image background
$imgur = imagecreatetruecolor($size, $size) or die('Cannot initialize new GD image stream');
//define the foreground and background colour
$fgcolour = imagecolorallocate($imgur, $r, $g, $b);
$bgcolour = imagecolorallocate($imgur, $backR, $backG, $backB);
//fill the image with the background colour
imagefill($imgur, 0, 0, $bgcolour);
//draw the rectangle using coordinates defined by the functions paramters
imagefilledrectangle($imgur, $posX, $posY, ($posX + $length), ($posY - $height), $fgcolour);
//output the header to tell browser this is a png
header ('Content-type: image/png');
//Write the image to be a png out
imagepng($imgur);
imagedestroy($imgur);
}
and is inside of a file called square.php
However when I try to use include "square.php"; in a seperate php file for example:
<?php
include '../../../square.php';
echo squareFunction(400,0,0,0,100,100,100,0,50,50,50);
?>
I just get a broken image link.
I then tried to include a function call at the top of my square.php file, but then when I used the include statement it would just print the square as soon as the include was read and did no other statements in my file.
Sorry for the lengthy post but I have been researching this all week and could not find any information on why this was happening, thank you all in advance.
I have a simple PHP script that enables users to upload images on a server. I am after some help in displaying these images as thumbnails in an HTMl page and then letting the user click on these thumbnails and then the original picture is displayed in a new page.
Can I use straight HTML for this? Or do I need some combination of javascript or PHP variant?
I know that there are many questions about this on stackoverflow, and I have tried them, but nothing is what I am after.
I would prefferably like the thumbnails be created on the 'fly' rather than me personally having to create each thumbnal when a user uploads an image.
So basically what language should I use to do this? And also can I have some source code if possible?
thanks
Creating thumbnails every time they are requested is a very bad idea - it takes a lot of processing power, which would be easily saved by keeping them around the first time you create them. I would suggest putting the thumbnail creation in the php script that processes the file upload, so that you save the image and its thumbnail to disk at the same time. You can also keep the thumbnail in memory, or wait until the first time it's requested to create it, but either way you cannot re-generate it every time it is requested.
It is possible to use html to change an image's size, by simply setting the width and/or height properties:
<img src='foo.jpg' alt='foo' width='500' height='300'/>
However, this is a bad idea if you aren't certain that the user will later want to view the full-sized image. The reason is that a thumbnail has a smaller filesize than the full image: if the client only wants to view the thumbnail, then you don't want to waste bandwidth (= your money and the client's time) sending them the full image.
As for your interface, you don't need javascript to accomplish that, just html. However, you will need a server-side script to create the thumbnails that your html page links to.
There are plenty of php thumbnail scripts out there.
Either you use a rewriter to still show the original path, but server a php thumbnail version. Or you have to have the url change to something like:
<img src="thumb.php?file=path/to/picture.jpg&size=128" />
Mighty Stuff
phpThumb
Are just such two. Best configured to utilize the cached folder. I use a modified version of the first script at work.
Here's a PHP script you can build appon only works with jpg images.
It will scan through a directory, normalize the image to a decent dimension and also make a thumb on the fly, then on next refresh it wont need to reprocess the image as its already present in the thumbs dir. Hope it helps...
Script placement
Root>
thisscript.php
/images/
someimage.jpg
someimage2.jpg
thisscript.php
<?php
// config section
$path = "./images/";
$thpath = $path."thumbs/";
// end configration
// Open the directory
$do = dir($path);
// now check if the thumb dir is available if not, create it!!
if (!is_dir($thpath)){
mkdir($thpath);
}
$output = '<div>';
while (($file = $do->read()) !== false){
if (is_dir($path.$file)){
continue;
}else{
$info = pathinfo($path.$file);
$fileext = $info['extension'];
if (strtolower($fileext) == 'jpg'){
if (!is_file($thpath.$file)){
//Normalize Super lrg Image to 750x550
thumb_it($path, $file, $path,750,550,99);
//Make Thumb 200x125
thumb_it($path, $file, $thpath,200,125,99);
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}else{
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}
}
}
}
$output .='</div>';
echo $output;
//Functions
function thumb_it($dirn, $file, $thumbdir,$rwidth,$rheight,$quality){
set_time_limit(0);
$filename = $dirn.$file;
$thfilename = $thumbdir.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $file);
// get the filename and the thumbernail directory
if (is_file($filename)){
// create the thumbernail from the original picture
$im = #ImageCreateFromJPEG($filename);
if($im==false){return false;}
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
if (($width < $rwidth) && ($height < $rheight)){
$n_height = $height;
$n_width = $width;
}else{
// saveing the aspect ratio
$aspect_x = $width / $rwidth;
$aspect_y = $height / $rheight;
if ($aspect_x > $aspect_y){
$n_width = $rwidth;
$n_height = $height / $aspect_x;
}else{
$n_height = $rheight;
$n_width = $width / $aspect_y;
}
}
$newimage = imagecreatetruecolor($n_width, $n_height);
// resizing the picture
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
// writing to file the thumbnail
if(file_exists($thfilename)){chmod($thfilename, 0777);}
Imagejpeg($newimage, $thfilename, $quality);
imagedestroy($newimage);
imagedestroy($im);
}
}
?>
I have a variable ($output) that is set to a string.
To mekt this string an image I'm using the PHP: GD Library.
In particular the imagestring() function, which I'm using with a very slight modification:
<?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, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
This is working as expected: It turns $output into an image.
So, my problem is (or my best guess at least):
header('Content-type: image/png');
Which, doesn't allow me to output any html after that.
So I read this question, which asks if you can use two headers, which you can't, but the accepted answer recommends, something like this: <img src="my_img.php" />
This of course would be fine, except I don't know how would this solve my issues since, since even if I knew the source to this image (which I don't - so, that would be my first question, what's the path to the generated image*) I't would change the fact that the header is there and is not letting me output text.
So, I how would you approach this issue?
Thanks in advance!!
*I guess that would solve my issues since I could do this on an external file, and the just call the image (but maybe not since I would have to do an include and this would include the header too) as you see I'm a bit confused. Sorry :)
UPDATE:
So I'm seeing my question was confusing so I will add some more code to see if this clarifies my problem a little bit more:
<?php
$x = mt_rand(1,5);
$y = mt_rand(1,5);
function add($x, $y) { return $x + $y; }
function subtract($x, $y) { return $x - $y; }
function multiply($x, $y) { return $x * $y; }
$operators = array(
'add',
'subtract',
'multiply'
);
$rdno = $operators[array_rand($operators)];
$result = call_user_func_array($rdno, array($x, $y));
session_start();
$_SESSION['res'] = $result;
if ($rdno == "add") {
$whato = "+";
}elseif ($rdno == "subtract") {
$whato = "-";
} else {
$whato = "*";
}
$output = $x . $whato . $y . " = ";
?>
<form name="input" action="check.php" method="post">
<input type="text" name="result" />
<input type="submit" value="Check" />
</form>
I want $output to be a image so this got me trying to use the PHP:GD script above, but I can't make put in the same file because of the header.
You need to make a separate PHP script which serves the image, then make an <img> tag that points to this script.
You can send information to the script using the querystring in the image URL.
Morbo says: "Windmills do not work that way! Goodnight!"
Which means that you need to bone up on how this all works. This issue points to you having a basic misunderstanding of your tools. HTML can't contain images, it contains links to images. So your script needs to be included from another page via an image tag. (or CSS)
However, all this is a good thing. It means that this script can have dynamic elements that produce a new image each time it is called. Or that it could password-protect your images so only logged-in users can see it.
There are a host of ways to use this. And once you realize the image is like a page to php, this opens new routes. Php can output anything. Word docs, excel, pdf, css, even JS. all of which can be used to do cool things.
Just think of the image as a separate page. You'll get it. It'll just click into place in your mind. One of those big 'aha' moments.
First, the path.
From the manual :
imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )
It means that if you don't give a second argument (it is the case here), you don't have the path to a file but the data of the file / image ressource. The php file will be understand as a png file by the browser thanks to the header you give.
Second :
In your page (ie index.php), you could add this like that
<img src="myimg.php?output=[...]" />
and in your php script myimg.php you have it like this :
<?php
$output = $_GET['output'] // getting your text
// 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, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
2 separates files.
You can send the image inline with echo '<img src="data:image/png;base64,'. base64_encode(imagepng($im)) .'" /> instead of <img src="my_img.php">.
Do not set a content-type header! Your output is text/html what you don't have to announce as it's the default in most server setups.
HTTP doesn't work that way. When your are serving image/png data, it as if you are serving a png file from the site, not an html file with an image in it. What are you trying to accomplish?
my_img.php is not source to your image. It is a source to the script generating that image, or reading it from file and outputting directly into browser. Obviously the approach with img src would be the best, because you'll hide all "boring" implementation of displaying image string behind browser's mechanisms.