如何通过 C# 代码在 Android 上的 Unity3D 中创建图像缩略图?
How to create an Image Thumbnail in Unity3D on Android through C# code?
我在 Unity 中有一些 C# 代码可以从我的 Android 设备的文件系统中抓取一张大图像,现在我想用它来创建一个小缩略图图像。
我发现了很多关于如何执行此操作的不同建议,例如:
MemoryStream outputStream = new MemoryStream();
System.Drawing.Image image = System.Drawing.Image.FromFile(originalImagePath);
System.Drawing.Image thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight,()=>false, IntPtr.Zero);
thumbnail.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return outputStream;
但是,与上述方法一样,我发现的所有方法都要求您使用 System.Drawing 命名空间。而且我这辈子都无法让这个命名空间中的函数在 Android 上工作,因为即使在将 "System.Drawing.dll" 添加到 Assets 文件夹后,我也会收到一条错误消息,说它无法定位"gdiplus.dll" 关于 "System.Drawing.Image" 的构建。我尝试下载并添加 said "gdiplus.dll" 到 Assets,但我得到了同样的错误,就好像找不到它一样!
我不明白为什么 System.Drawing 函数在 Unity 中工作如此困难,但这有点离题了,因为我真正想做的是创建一个实时图像的缩略图在用户的 Android 设备上。欢迎任何建议!
编辑:我忘了提到我想避免使用 Texture2D 的解决方案,因为它们不能 运行 离开主线程,因此会带来性能后果 =(
提前致谢! =)
不要使用Texture2D.Resize
,因为生成的纹理会变成灰色:
After resizing, texture pixels will be undefined.
有关其他解决方案,请参阅 this post。
旧答案
我建议使用开源的 C# 图像处理库,例如 ImageSharp or search it on GitHub。
如果第三方库的性能或大小仍然不够好,最后的解决方案是自己写一个。
以下是我能想到的两个想法:
- 将可能冗长的读取和调整大小过程拆分为多个
Coroutines
。
- 使用多线程
您也可以试试calling java functions from Unity3D。但是我不熟悉那个。
我在 Unity 中有一些 C# 代码可以从我的 Android 设备的文件系统中抓取一张大图像,现在我想用它来创建一个小缩略图图像。
我发现了很多关于如何执行此操作的不同建议,例如:
MemoryStream outputStream = new MemoryStream();
System.Drawing.Image image = System.Drawing.Image.FromFile(originalImagePath);
System.Drawing.Image thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight,()=>false, IntPtr.Zero);
thumbnail.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return outputStream;
但是,与上述方法一样,我发现的所有方法都要求您使用 System.Drawing 命名空间。而且我这辈子都无法让这个命名空间中的函数在 Android 上工作,因为即使在将 "System.Drawing.dll" 添加到 Assets 文件夹后,我也会收到一条错误消息,说它无法定位"gdiplus.dll" 关于 "System.Drawing.Image" 的构建。我尝试下载并添加 said "gdiplus.dll" 到 Assets,但我得到了同样的错误,就好像找不到它一样!
我不明白为什么 System.Drawing 函数在 Unity 中工作如此困难,但这有点离题了,因为我真正想做的是创建一个实时图像的缩略图在用户的 Android 设备上。欢迎任何建议!
编辑:我忘了提到我想避免使用 Texture2D 的解决方案,因为它们不能 运行 离开主线程,因此会带来性能后果 =(
提前致谢! =)
不要使用Texture2D.Resize
,因为生成的纹理会变成灰色:
After resizing, texture pixels will be undefined.
有关其他解决方案,请参阅 this post。
旧答案
我建议使用开源的 C# 图像处理库,例如 ImageSharp or search it on GitHub。
如果第三方库的性能或大小仍然不够好,最后的解决方案是自己写一个。
以下是我能想到的两个想法:
- 将可能冗长的读取和调整大小过程拆分为多个
Coroutines
。 - 使用多线程
您也可以试试calling java functions from Unity3D。但是我不熟悉那个。