【问题标题】:Convert a Bitmap image into a texture or material将位图图像转换为纹理或材质
【发布时间】:2016-10-26 10:12:11
【问题描述】:

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

我正在将 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'

我不清楚是否需要将托管转换为非托管。

【问题讨论】:

  • bmp 转换为纹理?但是您的代码中有jpg 而不是bmp
  • @Programmer 图像变成bmp之后 grayImage = gs.Apply(image);行
  • 您说要从 bmp 转换,但您正在加载 jpg 文件 FromFile("rip.jpg");。为什么不试试bmp?最重要的问题是 bmp 数据的来源是什么?从文件、互联网(WWW 或 UnityWebRequest)还是字节?
  • Aforge.NET(我没试过这个)应该有一个TextureTools.FromBitmap 方法:aforgenet.com/framework/docs/html/…
  • 我有一个个人图像,它是 JPG > 我将其转换为 BMP 以便能够应用 AForges 方法(在这种情况下使其成为灰度) > 接下来我希望能够将其用作纹理直接来自代码。

标签: c# unity3d aforge


【解决方案1】:

通过阅读您的代码,问题应该是“如何将 UnmanagedImage 转换为 Texture 或 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;

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2013-06-16
    • 2012-10-24
    • 2020-03-04
    • 1970-01-01
    • 2013-02-02
    • 2019-09-29
    • 1970-01-01
    • 2018-09-07
    相关资源
    最近更新 更多