Unity load medias from folder and display on RawImage

First I am trying to get it to work with just images.

I’m very new with Unity and not good with C#. I’m able to get all
media file sources (images) to an array but next I need to convert
them to a texture and place on the RawImage -component. I’m stuck with
this part.

You are looking for the Texture2D.LoadImage function. It converts image bytes to Texture2D then you can assign that Texture2D to the RawImage.

You have to ask new question about how to do this with Videos. That’s much more complicated.

public RawImage rawImage;
Texture2D[] textures = null;

//Search for files
DirectoryInfo dir = new DirectoryInfo(@"C:\medias");
string[] extensions = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ogg", ".OGG" };
FileInfo[] info = dir.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();

//Init Array
textures = new Texture2D[info.Length];


for (int i = 0; i < info.Length; i++)
{
    MemoryStream dest = new MemoryStream();

    //Read from each Image File
    using (Stream source = info[i].OpenRead())
    {
        byte[] buffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }
    }

    byte[] imageBytes = dest.ToArray();

    //Create new Texture2D
    Texture2D tempTexture = new Texture2D(2, 2);

    //Load the Image Byte to Texture2D
    tempTexture.LoadImage(imageBytes);

    //Put the Texture2D to the Array
    textures[i] = tempTexture;
}

//Load to Rawmage?
rawImage.texture = textures[0];

Leave a Comment