I want to store my image create from string into database in php.But there is a error.It shows an error message. The message is : Undefined array key 1 in on line : 第行
: Undefined array key 1 in on line : 第行
Any ideas how i can solve/fix this.Thanks in advance...
Here is my demo code...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>click</button>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(){
let text = "What is Lorem Ipsum?Lorem Ipsum is ";
$.ajax({
url:'create_image_php.php',
type:'post',
data:{"text":text},
success:function(data){
alert(data);
console.log(data);
}
})
})
})
</script>
</body>
</html>
create image_php.php
<?php
$text = $_POST['text'];
$image_width = 320; // pixels
text_to_image($text, $image_width);
function text_to_image($text, $image_width, $colour = array(0,244,34), $background = array(0,0,0))
{
include 'conn.php';
$font = 5;
$line_height = 30;
$padding = 10;
$text = wordwrap($text, ($image_width/10));
$lines = explode("\n", $text);
$image = imagecreate($image_width,480);
$background = imagecolorallocate($image, $background[0], $background[1], $background[2]);
$colour = imagecolorallocate($image,$colour[0],$colour[1],$colour[2]);
imagefill($image, 0, 0, $background);
$i = $padding;
foreach($lines as $line){
imagestring($image, $font, $padding, $i, trim($line), $colour);
$i += $line_height;
}
ob_start();
imagepng($image);
$image= printf('data:image/png;base64,%s', base64_encode(ob_get_clean()));
$image_array_1 = explode(";", $image);
$image_array_2 = explode(",", $image_array_1[1]);
$image = base64_decode($image_array_2[1]);
$imageName = time() . '.png';
$image = file_put_contents($imageName, $image);
$image_file = addslashes(file_get_contents($imageName));
$sql = "INSERT INTO `images`(`image`) VALUES(:image_file)";
$stmt = $conn->prepare($sql);
$stmt->bindparam(':image_file',$image_file);
$query = $stmt->execute();
if($query){
echo "success";
}
else{
echo "error";
}
exit;
} ?>
conn.php
<?php
try{
$conn = new PDO("mysql:host=localhost;dbname=social_site","root","");
}
catch(PDOException $e){
echo "Error:".$e->getMessage();
}
?>
Table Name:images
index:image
$image= printf('data:image/png;base64,%s', base64_encode(ob_get_clean()));
the printf function is used for "Produces output according to format.", it returns the length of the output, not the result of format, try change this code to:
$image = 'data:image/png;base64,'.base64_encode(ob_get_clean();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.