起因:有个需求要批量按比例调整UI页面大小。并不是简单的缩放,是所有素材都需要按比例缩小。于是,图片首当其冲。这里记录一下解决方案,因为参考了挺多别人的事例,虽然都描述的都差不多,但大部分都只描述了方法,这里记录一下整个完整的方案。
环境:Unity2019.4.10f1
需求是是要把所有的图片按照从 1080×2160 到 720×1440 的等比缩小
直接上代码吧
public static void ChangeImageSize()
{
var oripath = Application.dataPath;
string path = oripath.Substring(0, oripath.LastIndexOf("/", oripath.LastIndexOf("/") - 1)) +
"/art/UIProject/assets";
DirectoryInfo direction = new DirectoryInfo(path);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
var index = 0;
EditorApplication.update = delegate()
{
bool isCancel =
EditorUtility.DisplayCancelableProgressBar("处理中...", files[index].Name,
(float) index / files.Length);
if (!files[index].Name.EndsWith(".png") && !files[index].Name.EndsWith(".jpg"))
{
index++;
}
else
{
string xmlName = files[index].Name.Split('.')[0];
var myBitmap = new System.Drawing.Bitmap(files[index].FullName);
var x = Mathf.CeilToInt(myBitmap.Width * 720 / 1080f);
var y = Mathf.CeilToInt(myBitmap.Height * 1440 / 2160f);
var b = new System.Drawing.Bitmap(x, y);
var g = System.Drawing.Graphics.FromImage(b);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(myBitmap, new System.Drawing.Rectangle(0, 0, x, y),
new System.Drawing.Rectangle(0, 0, myBitmap.Width, myBitmap.Height),
System.Drawing.GraphicsUnit.Pixel);
g.Dispose();
myBitmap.Dispose();
b.Save(files[index].FullName);
b.Dispose();
index++;
}
if (isCancel || index >= files.Length)
{
EditorUtility.ClearProgressBar();
EditorApplication.update = null;
if (isCancel)
{
EditorUtility.DisplayDialog("取消提示", "取消处理后需要把已处理的文件还原才能再次处理。", "确认");
}
if (index >= files.Length)
{
EditorUtility.DisplayDialog("图片处理完成", "处理一次即可,如果误操作,需要把对应目录下所有图片文件还原", "确认");
}
}
};
}
这里只是把图片的大小做了变更,其他的属性都可以类比一下更改。
当然需要注意的有一点,就是代码里使用的System.Drawing这个类Unity里面是不包含的。
我们可以通过在Plugins的目录下添加System.Drawing.dll这个文件来达到使用该类的目的。
另外也可以直接通过C#生成解决方案来处理。即直接使用C#使用 原始处理方案 部分代码生成windows桌面程序等来处理。因为很多工具在你创建C#方案时默认是包含该工具类的。
这种错误的话可以检查一下自己传递的参数有没有问题,因为你如果是计算出图片宽高的话,很有可能因为四舍五入导致某个数值为0,这时候可能就会报这个错误。
以上。
抽空把工具整理了一下,大家可以下载尝试一下。工程链接
可以下载下面这些来文件来使用。
功能大概就是指定文件或文件夹按格式来处理图片大小。
Original: https://blog.csdn.net/qq_39860954/article/details/127395695
Author: Gipsyz
Title: 使用 C# / Unity 进行图像处理
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/632866/
转载文章受原作者版权保护。转载请注明原作者出处!