Unity使用C#不失真修改图片的分辨率

unity每个项目都需要使用同一张图的不同的分辨率 icon,这样只要一个最大的分辨率图片就可以了,需要使用的时候直接修改图片的分辨率,用完还可以删除掉,是不是既方便又可以节省不少空间。不逼逼直接上脚本

修改图片分辨的方法:

public static Texture2D ReSetTextureSize(Texture2D tex, int width, int height)

{

var rendTex = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);

rendTex.Create();

Graphics.SetRenderTarget(rendTex);

GL.PushMatrix();

GL.Clear(true, true, Color.clear);

GL.PopMatrix();

var mat = new Material(Shader.Find("Unlit/Transparent"));

mat.mainTexture = tex;

Graphics.SetRenderTarget(rendTex);

GL.PushMatrix();

GL.LoadOrtho();

mat.SetPass(0);

GL.Begin(GL.QUADS);

GL.TexCoord2(0, 0);

GL.Vertex3(0, 0, 0);

GL.TexCoord2(0, 1);

GL.Vertex3(0, 1, 0);

GL.TexCoord2(1, 1);

GL.Vertex3(1, 1, 0);

GL.TexCoord2(1, 0);

GL.Vertex3(1, 0, 0);

GL.End();

GL.PopMatrix();

var finalTex = new Texture2D(rendTex.width, rendTex.height, TextureFormat.ARGB32, false);

RenderTexture.active = rendTex;

finalTex.ReadPixels(new Rect(0, 0, finalTex.width, finalTex.height), 0, 0);

finalTex.Apply();

return finalTex;

}

顺便这里 给大家写个图片的保存方法:

public static void SaveTexture(Texture2D tex, string toPath)

{

using (var fs = File.OpenWrite(toPath))

{

var bytes = tex.EncodeToPNG();

fs.Write(bytes, 0, bytes.Length);

}

}

再补充个图片自动压缩功能

public static bool CompressTexture(params string[] texturePath)

{

var shell = BabySystem.babyFrameWorkAbsolutePath + "TextureTools/";

if (BabySystem.activeBuildTarget == BuildTarget.iOS)

shell = shell + "mac/pngquant";

else

shell = shell + "win/pngquant.exe";

var strCmdText = "--ext .png " + "--force -- " + string.Join(" ",texturePath);

System.Diagnostics.Process process = new System.Diagnostics.Process();

System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

startInfo.FileName = shell;

startInfo.Arguments = strCmdText;

process.StartInfo = startInfo;

process.Start();

process.WaitForExit();

int ExitCode = process.ExitCode;

if (ExitCode != 0)

{

Debug.LogError("Run CMD CompressTexture Failed : "+ExitCode);

return false;

}

return true;

}


这边是这个压缩工具的下载地址:

压缩工具

你可能感兴趣的:(Unity使用C#不失真修改图片的分辨率)