unity3D -- 压缩图片
由于微信分享圖片要求圖片大小不能超過(guò)200k,有些手機(jī)的高清屏幕截下來(lái)的圖片肯定大于200k了,這個(gè)時(shí)候只能是壓縮圖片了,unity壓縮圖片的方法,直接上C#源代碼:
public?void?WXShareImage?(string?imagePath,?int?sceneType)
????{
????????byte[]?fileData?=?File.ReadAllBytes?(imagePath);
????????Texture2D?tex?=?new?Texture2D?((int)(Screen.width),?(int)(Screen.height),?TextureFormat.RGB24,?true);
????????tex.LoadImage?(fileData);
????????float?miniSize?=?Mathf.Max?(tex.width,?tex.height);
????????float?scale?=?1200.0f?/?miniSize;
????????if?(scale?>?1.0f)?{
????????????scale?=?1.0f;
????????}
????????Texture2D?temp?=?ScaleTexture?(tex,?(int)(tex.width?*?scale),?(int)(tex.height?*?scale));
????????byte[]?pngData?=?temp.EncodeToJPG?();
????????string?miniImagePath?=?imagePath.Replace?(".png",?"_min.jpg");
????????File.WriteAllBytes?(miniImagePath,?pngData);
????????Destroy?(tex);
????????Destroy?(temp);
????}
該函數(shù)的接受兩個(gè)參數(shù),一個(gè)是傳過(guò)來(lái)的圖片路徑,第二個(gè)參數(shù)是微信分享場(chǎng)景的id(微信文檔有)。
private?Texture2D?ScaleTexture?(Texture2D?source,?int?targetWidth,?int?targetHeight)
????{
????????Texture2D?result?=?new?Texture2D?(targetWidth,?targetHeight,?source.format,?true);
????????Color[]?rpixels?=?result.GetPixels?(0);
????????float?incX?=?((float)1?/?source.width)?*?((float)source.width?/?targetWidth);
????????float?incY?=?((float)1?/?source.height)?*?((float)source.height?/?targetHeight);
????????for?(int?px?=?0;?px?<?rpixels.Length;?px++)?{
????????????rpixels?[px]?=?source.GetPixelBilinear?(incX?*?((float)px?%?targetWidth),?incY?*?((float)Mathf.Floor?(px?/?targetWidth)));
????????}
????????result.SetPixels?(rpixels,?0);
????????result.Apply?();
????????return?result;
????}
該函數(shù)將圖片壓縮并返回壓縮后的圖片,壓縮后的大小由調(diào)用者傳過(guò)來(lái)。
源代碼功能把最后圖片轉(zhuǎn)成了JPG格式,要是想轉(zhuǎn)成PNG格式的話(huà),unity有相應(yīng)的方法,但是轉(zhuǎn)成PNG,圖片占用的內(nèi)存會(huì)更大,就不能壓縮成1200像素的了,要壓縮的更小,這個(gè)需要注意一下。
該方法我已經(jīng)測(cè)試過(guò),沒(méi)有問(wèn)題,所以才上的源代碼,圖就不傳了,反正壓縮前后的圖片截下來(lái)你也看不到變下了。
——Rocky
總結(jié)
以上是生活随笔為你收集整理的unity3D -- 压缩图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C文件操作——设置文件的位置指示器fse
- 下一篇: github镜像网站_Jenkins把G