如何从图像变量中存储和获取图像(SESSION)


How to store and get image from a image variable (SESSION)?

这是我的代码,test1.php工作,test2.php不工作。

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);
?>

可以看到,test1.php创建了一个随机图像。我可以使用:

<img src="test1.php">

显示test1.php在任何页面中的图像。但是,我想在其他php文件中使用if else语句。

例如:

如果用户点击提交按钮并没有输入任何内容(没有答案),图像将仍然相同,他们必须回答相同的问题。如果失败,图像将被更改。

我不想使用javascript来防止用户不输入任何内容并将图像存储在磁盘中。

所以,我认为我需要一个变量来存储可以再次使用的图像。但是我发现我不能使用上面的方法。

我怎样才能做到这一点?

imagecreate()返回代表给定图像的资源。PHP的会话不能存储资源类型的变量(更准确地说,PHP不能在脚本结束时序列化它们),参见http://php.net/manual/en/function.session-register.php:

注意:当前不可能注册资源变量会话。…

您可以将图像序列化为字符串并将该字符串存储到会话(未测试):

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']);

在不了解上下文的情况下,你不能做一些像

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);

多个参数示例:

将图像信息存储在数组中

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."'/>";

然后在test。php中调用它们