here is my code, test1.php works, test2.php not works.
test1.php:
<?php
session_start();
header('Content-type: image/jpeg');
$text = rand(1000,9999);
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
$_SESSION['image'] = $image;
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
test2.php:
<?php
session_start();
header('Content-type: image/jpeg');
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
As you can see, test1.php create a random image.
I can use:
<img src="test1.php">
to show the image from test1.php in any pages.
but, I want to use if else statement in other php files.
for example:
if users click submit button and enter nothing(no answer), the image will still the same, they have to answer the same question. if failed, the image will change.
I don't want to use javascript to prevent users input nothing and store images in disk.
so, I think that I need a variable to store the image that can be used again.
but I found I cannot use above method.
how can I achieve this?
imagecreate() returns a resource representing given image. PHP's sessions cannot store resource-type variables (more precisely - PHP is unable to serialize them upon script end), see http://php.net/manual/en/function.session-register.php:
Note: It is currently impossible to register resource variables in a
session. ...
You may serialize the image to a string and store this string to the session (not tested):
test1.php:
...
ob_start();
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();
$_SESSION['image'] = $contents;
test2.php:
header('Content-type: image/jpeg');
die($_SESSION['image']);
Without knowing much about the context, can't you do something like
session_start();
$_SESSION['randomValue'] = mt_rand(1000,9999);
if(someValueIsEntered){
$_SESSION['randomValue'] = mt_rand(1000,9999);
}
echo "<img src='test.php?random=".$_SESSION['randomValue']."'/>";
Test.php
$randomValue = filter_input(INPUT_GET, 'random');
header('Content-type: image/jpeg');
$text = $randomValue;
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
imagejpeg($image);
Multiple parameters example:
Store the information about the image in an array.
session_start();
if(!isset($_SESSION['imageData']){
$_SESSION['imageData'] = array(
"random" => mt_rand(1000,9999),
"x1" => mt_rand(0,10),
"x2" => mt_rand(0,10)
);
}
if(someValueIsEntered){
//Randomize array again.
}
$imageString = "test.php";
foreach ($_SESSION['imageData'] as $key => $value) {
$index = current($array);
if($index == 0) {
$seperator = "?";
} else {
$seperator = "&";
}
$imageString .= $seperator.$key."=".$value;
}
echo "<img src='".$imageString."'/>";
And just call them in the test.php then.
Related
I'm trying to create a script that takes a certain part of an image but when i use imagepng, it returns me this:
Here's my code
$name = $path;
header("Content-type: image/png");
if (strpos($name, '..') !== false) {
exit(); // name in path with '..' in it would allow for directory
traversal.
}
$size = $face_size > 0 ? $face_size : 100;
//Grab the skin
$src = imagecreatefrompng("./skins/" . $name . ".png");
//If no path was given or no image can be found, then create from default
if (!$src) {
$src = imagecreatefrompng("./skins/default.png");
}
//Start creating the image
list($w, $h) = getimagesize("./skins/" . $name . ".png");
$w = $w / 8;
$dest = imagecreatetruecolor($w, $w);
imagecopy($dest, $src, 0, 0, $w, $w, $w, $w); // copy the face
// Check to see if the helm is not all same color
$bg_color = imagecolorat($src, 0, 0);
$no_helm = true;
// Check if there's any helm
for ($i = 1; $i <= $w; $i++) {
for ($j = 1; $j <= 4; $j++) {
// scanning helm area
if (imagecolorat($src, 40 + $i, 7 + $j) != $bg_color) {
$no_helm = false;
}
}
if (!$no_helm)
break;
}
// copy the helm
if (!$no_helm) {
imagecopy($dest, $src, 0, -1, 40, 7, $w, 4);
}
//prepare to finish the image
$final = imagecreatetruecolor($size, $size);
imagecopyresized($final, $dest, 0, 0, 0, 0, $size, $size, $w, $w);
//if its not, just show image on screen
imagepng($final);
//Finally some cleanup
imagedestroy($dest);
imagedestroy($final);
I used this code previously without any framework and it worked just fine, I don't know where it comes from.
Laravel and other frameworks use Middlewares, so when your controller method is done the application isn't ready to send the response yet. You can solve the problem by storing the output of the imagepng function in an internal buffer and send it properly(I think there isn't another solution if you want to use GD), also you have to use Laravel's function to set the HTTP headers instead of the header function.
Here is a simple example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AppController extends Controller
{
//Generates an image with GD and sends it to the client.
public function image(){
$im = imagecreatetruecolor(800, 420);
$orange = imagecolorallocate($im, 220, 210, 60);
imagestring($im, 3, 10, 9, 'Example image', $orange);
//Turn on output buffering
ob_start();
imagepng($im);
//Store the contents of the output buffer
$buffer = ob_get_contents();
// Clean the output buffer and turn off output buffering
ob_end_clean();
imagedestroy($im);
return response($buffer, 200)->header('Content-type', 'image/png');
}
}
You can look at this, I hope it will help you.
Although it works, it isn't the best method, I recommend you to use Imagick(if you can) instead of GD.
I want to create an image with text and store in temp without output to browser
I have used the following code:
header("Content-type: image/jpeg");
$imgPath = 'images/certificate.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = $userid;
$fontSize = 3;
$x = 115;
$y = 185;
imagestring($image, $fontSize, $x, $y, $string, $color);
imagejpeg($image,'images/certi.jpg');
imagedestroy($image);
When using imagejpeg to save a file, you do not need the header header("Content-type: image/jpeg"); line
If you are not returning image data, then you should not be setting the header.
Remove the header("Content-type: image/jpeg");
I'm not clear on exactly what you're trying to do, but if the work has been done, there is no need to return any output, if output is not desired.
I am doing my project in CodeIgniter. I am trying to call captcha.php file in index file.This captcha file in folder files. Currently, the captcha image is not viewing. I need to display random numbers in image.
captcha.php
<?php
session_start();
$string = '';
for ($i = 0; $i < 5; $i++) {
$string .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $string;
$dir = 'fonts/';
$image = imagecreatetruecolor(165, 50);
// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
$font = "PT_SANS-BOLD_1.TTF"; // font style
}
else
{
$font = "PT_SANS-ITALIC_1.TTF";// font style
}
// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
$color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
$color = imagecolorallocate($image, 163, 197, 82);// color
}
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['random_number']);
header("Content-type: image/png");
imagepng($image);
?>
in html file
<img src="<?= base_url();?>files/captcha.php" alt="" id="captcha" />
This is not an answer to your question but alternative you could opt for.
So many captcha scripts are already available may be you can use some of that instead of coding it again.
Check this
If you do go for this option then do make sure that fonts are placed in right places.
I have a pictures website like Quickmeme.com and I would like to add text over images.
I currently let the user upload the picture manually, writing the comments with Paint program in Windows which is a bad idea and I need help ...
here is the code I use for Uploading an image, I am thinking of adding a text field below the upload field so what ever the user writes in that box will be printed on the image as an imagetext ... So how can I do that with php?
<?php if(isset($_POST["upload"])){
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
if(move_uploaded_file($tmp_name, $directory)){
if(mysql_query("")){
$query = mysql_query(""); $fetch = mysql_fetch_array($query);
if(mysql_query("")){
header("Location: index.php");
exit;
}
}
}
} ?>
Here is my website http://www.picturepunches.net
You can try
if (isset($_POST["upload"])) {
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
case "jpg" :
$im = imagecreatefromjpeg($_FILES["file"]["tmp_name"]);
break;
case "gif" :
$im = imagecreatefromgif($_FILES["file"]["tmp_name"]);
break;
case "png" :
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
break;
default :
trigger_error("Error Bad Extention");
exit();
break;
}
$font = 'verdana.ttf';
$grey = imagecolorallocate($im, 128, 128, 128);
$red = imagecolorallocate($im, 255, 0, 0);
// Add some shadow to the text
imagettftext($im, 10, 0, 11, 20, $grey, $font, $date);
imagettftext($im, 10, 0, 10, 35, $grey, $font, $time);
imagettftext($im, 10, 0, 10, 50, $red, $font, $random);
// imagepng($im);
imagedestroy($im);
if (move_uploaded_file($tmp_name, $directory)) {
if (mysql_query("")) {
$query = mysql_query("");
$fetch = mysql_fetch_array($query);
if (mysql_query("")) {
header("Location: index.php");
exit();
}
}
}
}
Output
Uploaded Final
First, check if you have the GD extension installed, next,
Use the GD functions
//Loading the file
$rImg = ImageCreateFromJPEG("MyPicture.jpg");
//Font Color (black in this case)
$color = imagecolorallocate($rImg, 0, 0, 0);
//x-coordinate of the upper left corner.
$xPos = 100;
//y-coordinate of the upper left corner.
$yPos = 30;
//Writting the picture
imagestring($rImg,5,$xPos,$yPos,"My text in the picture",$color);
//The new file with the text
header('Content-type: image/jpeg');
imagejpeg($rImg, NULL, 100);
you can use this tutorial
http://blog.doh.ms/2008/02/12/adding-text-to-images-in-real-time-with-php/
i used captcha coding in my form.the following is the coding of captcha creation
<?php
session_start();
$string = '';
for ($i = 0; $i < 5; $i++)
{
$string .= chr(rand(97, 122));
}
$_SESSION['rand_code'] = $string;
$dir = 'fonts/';
$image = imagecreatetruecolor(150,60) or die('Cannot Initialize new image ');
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 200, 100, 90);
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,50,150,100,$black);
imagettftext ($image, 30, 0, 10, 40, $color, $dir."BauhausMedium.ttf", $_SESSION['rand_code']);
header("Content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);
?>
In other page i call this code using img tag.
but the problem is, In that page i want captcha image in textbox.i used $_session['rand_code']; but i displays previous session value that is previous captcha image value.
i want current image value in that page?
You are accessing the captcha code after you load the form, because the image in the form actually triggers the captcha code.
You should only check the captcha after the form is submitted.
One way to go is to create the random code and save it in the session at the page that will have the img tag. And at the page that the image is created just read the session.