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

本文关键字:纹理 位图 图像 转换 | 更新日期: 2023-09-27 18:14:54

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

我正在使用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到纹理或Texture2D"因为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的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;