c# - Unity从文件夹加载媒体并显示在RawImage上

标签 c# image unity-game-engine resources media-player

我正在尝试在 Unity 中创建一个媒体播放器,它从静态文件夹中读取所有媒体文件并播放所有媒体(图像静态持续时间、视频长度的视频)。首先,我试图让它只处理图像。

我对 Unity 很陌生,不太擅长 C#。我能够将所有媒体文件源(图像)获取到一个数组,但接下来我需要将它们转换为纹理并放置在 RawImage 组件上。我被这部分困住了。

如果我有 src(例如 C:\medias\img1.jpg),那么如何将其作为图像放置在 RawImage 组件上?

我的代码 ->

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System;
using System.IO;
using System.Linq;

public class Player : MonoBehaviour {

    // Use this for initialization
    void Start () {
        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();
        Debug.Log (info[0]);
        // Logs C:\medias\img1.jpg
    }

    // Update is called once per frame
    void Update () {

    }
}

谢谢:)

最佳答案

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.

您正在寻找Texture2D.LoadImage功能。它将图像字节转换为Texture2D,然后您可以将该Texture2D分配给RawImage。

您必须提出有关如何使用视频执行此操作的新问题。这要复杂得多。

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

关于c# - Unity从文件夹加载媒体并显示在RawImage上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42623578/

相关文章:

c# - DICOM库-支持所有DICOM传输语法

python - 使用python增加图像中特定像素的亮度

php - 上传文件 PHP 时生成唯一文件名的最佳方法

image - 使文本字符串填充矩形

c# - 如何统一更改克隆的排序?

c# - razor 页面,如何将 json 序列化字符串传递到模型属性中

c# - 将地址与地址列表进行比较

c# - LINQ 方法将集合分组为具有指定元素数量的子组

c# - 统一2D : animator single frame animations - instant transition

performance - 仅当游戏对象靠近 Controller /摄像机时才渲染它们