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

时间:2016-10-26 10:12:11

标签: c# unity3d aforge

我看到很多程序员想要转换内容INTO Bitmap,但是我无法找到适合相反问题的解决方案。

我正在使用带有Unity的AForge.net,我正试图通过将处理后的图像应用到多维数据集来测试它。

我目前的代码如下:

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'

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

1 个答案:

答案 0 :(得分:1)

通过阅读您的代码,问题应该是&#34; 如何将UnmanagedImage转换为Texture或Texture2D &#34;因为UnmanagedImage(final变量)存储来自UnmanagedImage.FromManagedImage的转换后的图像。

UnmanagedImage有一个名为ImageData的属性,它返回IntPtr

幸运的是,Texture2D至少有两个函数可以加载来自IntPtr的纹理。

您的final变量属于UnmanagedImage

1 。使用Texture2D的构造函数Texture2D.CreateExternalTexture及其补充函数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&#39; LoadRawTextureData及其补充功能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;