I have 4 images in my database and I want to display all 4 of them in unity. What I am doing is that I am using base64_encode function in php to display my image as a string in browser and then unity is converting that string into an image but the problem is that it is treating string of all 4 images and as 1 and only showing the first one.
I have tried separating string by
in php but unity can't understand line changing and I have no idea how to separate them. Once they are separated ik I can make a string array and save them in it.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "picture";
//Make connection
$conn = new mysqli($servername, $username, $password, $dbName);
//Check connection
if(!$conn)
{
die("Connection failed.". mysqli_connect_error());
}
//
//else echo("Connection success") . "<br>";;
$sql = "SELECT * FROM images";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
//show data for each row
while($row = mysqli_fetch_assoc($result))
{
//echo '<img src="data:image/jpeg;base64,'.base64_encode($row['pics']).'"/>';
echo "".base64_encode($row['pics']);
}
}
?>
private string imageString = "";
private void Start()
{
StartCoroutine(GetImage());
}
IEnumerator GetImage()
{
WWWForm imageForm = new WWWForm();
WWW wwwImage = new WWW("http://localhost/Insert_Images/index.php");
yield return wwwImage;
imageString = (wwwImage.text);
}
private void OnGUI()
{
byte[] Bytes = System.Convert.FromBase64String(imageString);
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(Bytes);
GUI.DrawTexture(new Rect(200, 20, 440, 400), texture, ScaleMode.ScaleToFit, true, 1f);
}
The result should be 4 separate images but it is only showing one.
The issue here is that your code will output all four images after each other while your code in Unity gets the complete output and displays it as one image.
Instead of outputting all the images in one big chunk as you are right now, you can output your data as a json array which you then parse in Unity and create each image separately.
To create the json in PHP, you can do this:
// Create an array in which we will save the images and then encode as json
$images = [];
while($row = mysqli_fetch_assoc($result))
{
// Add the image to the array
$images[] = base64_encode($row['pics']);
}
// Let the client know what type of content we're returning
header('Content-Type: application/json');
// Encode the array as json and output it
echo json_encode($images);
// Exit the script to make sure that we don't get any unwanted output after the json
exit;
That will output a json array. You will need to look up how to parse json in Unity (I know that there are support for it) and just iterate through the array and create output the image on each iteration.