将位图图像转换为纹理或材质

Convert a Bitmap image into a texture or material

我看到很多程序员想要将东西转换成位图,但我找不到适合的解决方案来解决相反的问题。

我将 AForge.net 与 Unity 一起使用,我正在尝试通过将处理过的图像应用到立方体来对其进行测试。

我当前的代码如下所示:

using UnityEngine;
using System.Collections;
using System.Drawing;
using AForge;
using AForge.Imaging;
using AForge.Imaging.Filters;

public class Test : MonoBehaviour {

    // Use this for initialization
    public Renderer rnd;
    public Bitmap grayImage;
    public Bitmap image;
    public UnmanagedImage final;
    public byte[] test;

    Texture tx;
    void Start () {


        image = AForge.Imaging.Image.FromFile("rip.jpg");

        Grayscale gs = new Grayscale (0.2125, 0.7154, 0.0721);
        grayImage = gs.Apply(image);
        final = UnmanagedImage.FromManagedImage(grayImage);

        rnd = GetComponent<Renderer>();
        rnd.enabled = true;
    }

    // Update is called once per frame
    void Update () {
        rnd.material.mainTexture = final;
    }
}

我在行 rnd.material.mainTexture = final; 中收到以下错误:

Cannot implicitly convert type 'AForge.Imaging.UnmanagedImage' to 'UnityEngine.Texture'

我不清楚是否需要从托管到非托管的转换。

通过阅读您的代码,问题应该是“如何将 UnmanagedImage 转换为 Texture 或 Texture2D”,因为 UnmanagedImage(final 变量) 存储从 UnmanagedImage.FromManagedImage.

UnmanagedImage has a property called ImageData 其中 returns IntPtr

幸运的是,Texture2D 至少有两个从 IntPtr.

加载纹理的函数

您的 final 变量是 UnmanagedImage 的类型。

1.使用Texture2D的构造函数Texture2D.CreateExternalTexture and it's complimentary function UpdateExternalTexture.

Texture2D convertedTx;
//Don't initilize Texture2D in the Update function. Do in the Start function
convertedTx = Texture2D.CreateExternalTexture (1024, 1024, TextureFormat.ARGB32 , false, false, final.ImageData);

//Convert UnmanagedImage to Texture
convertedTx.UpdateExternalTexture(final.ImageData);
rnd.material.mainTexture = convertedTx;

2.使用Texture2D的LoadRawTextureData and it's complimentary function Apply.

Texture2D convertedTx;
//Don't initilize Texture2d in int the Update function. Do in the Start function
convertedTx = new Texture2D(16, 16, TextureFormat.PVRTC_RGBA4, false);

int w = 16;
int h = 16;
int size = w*h*4;

//Convert UnmanagedImage to Texture
convertedTx.LoadRawTextureData(final.ImageData, size);
convertedTx.Apply(); //Must call Apply after calling LoadRawTextureData

rnd.material.mainTexture = convertedTx;