Unity 代码集锦之图片处理

1、将Texture2D保存为jpg

    void TestSaveImageToJPG(Texture2D buffer)
    {
        File.WriteAllBytes("F:/output.jpg", buffer.EncodeToJPG());
    }

2、将图片的原始数据保存至txt

    void TestSaveImageToTXT(Texture2D buffer)
    {
        byte[] rawData= buffer.GetRawTextureData();
        //byte[] bt = ChangeRGB(rawData).GetRawTextureData();//转换RGB
        //char[] ch = Encoding.ASCII.GetChars(bt);//byte[]转为char[]
        StreamWriter sw = new StreamWriter(@"F:\\output.txt"); //保存到指定路径
        for (int i = 0; i < rawData.Length; i++)
        {
            sw.Write(rawData[i]);
            sw.Write(' ');
        }
        sw.Flush();
        sw.Close();
    }

  

3、转换图片的RGB

    Texture2D ChangeRGB(Texture2D source)
    {
        Texture2D result = new Texture2D(source.width, source.height, TextureFormat.RGB24, false);
        for (int i = 0; i < result.height; ++i)
        {
            for (int j = 0; j < result.width; ++j)
            {
                Color newColor = source.GetPixelBilinear((float)j / (float)result.width, (float)i / (float)result.height);
                float temp = newColor.r;
                newColor.r = newColor.b;
                newColor.b = temp;
                result.SetPixel(j, i, newColor);
            }
        }
        result.Apply();
        return result;
    }

  

4、将Texture转为Texture2D,参数可传入Texture也可传入WebCamTexture类型的参数,和上述的“1”配合使用,可将摄像头的数据保存为图片

    Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);
        return texture2D;
    }

  

 5、屏幕截图

        Texture2D frameBuffer;
        Rect camRect;
        frameBuffer = new Texture2D(width, height, TextureFormat.RGB24, false, false);
        camRect = new Rect(0, 0, width, height);
        frameBuffer.ReadPixels(camRect, 0, 0);
        frameBuffer.Apply(); 

  

  

猜你喜欢

转载自www.cnblogs.com/Jason-c/p/10812805.html
今日推荐