分享

Unity中关于保存图片到Android/IOS相册中的问题

 cgarts 2016-01-28

       我们在一些项目中可能需要截图保存功能(特别是AR的一些项目),将截下来的图保存的相册中,从而实现分享功能。下面就Android和IOS说一下他们是如何将图片保存到本地图册的。

关于安卓端,保存到相册方法很简单,就是也路径的问题,具体方法如下:

public class takephoto : MonoBehaviour
{
    private int i = 0;
    //UI
    public GameObject[] btn;
    //存储路径
    private string Path_save;
    //读取路径
    private string Path_read;
    private string filepath;
    private string destination;
    void Start()
    {
        filepath = Application.persistentDataPath + "/test.txt";
    }
    void OnClick()
    {
        StartCoroutine(getTexture2d());
    }
    IEnumerator getTexture2d()
    {
        //隐藏UI
        for (int j = 0; j < btn.Length; j++)
        {
            btn[j].GetComponentInChildren<UISprite>().enabled = false;
        }
        //截图操作
        yield return new WaitForEndOfFrame();
        Texture2D t = new Texture2D(Screen.width, Screen.height,TextureFormat.RGB24,false);
        //显示UI
        for (int j = 0; j < btn.Length; j++)
        {
            btn[j].GetComponentInChildren<UISprite>().enabled = true;
        }
        t.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, true);
        byte[] bytes = t.EncodeToPNG();
        t.Compress(true);
        t.Apply();

        //获取系统时间
        System.DateTime now = new System.DateTime();
        now = System.DateTime.Now;
        string filename = string.Format("image{0}{1}{2}{3}.png", now.Day, now.Hour, now.Minute, now.Second);
        //记录每一个截图名字
        StreamWriter sw;
        FileInfo ft = new FileInfo(filepath);
        if (!ft.Exists)
        {
            sw = ft.CreateText();
        }
        else
        {
            sw = ft.AppendText();
        }
        sw.WriteLine(filename);
        sw.Close();
        sw.Dispose();
        //应用平台判断,路径选择
        if (Application.platform == RuntimePlatform.Android)
        {
            string origin = Path_save;
            destination = "/mnt/sdcard/DCIM/ARphoto";
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            destination = destination + "/" + filename;
            Path_save = destination;
       
        }
        //保存文件
        File.WriteAllBytes(Path_save, bytes);
    }

}



其中主要的就是安卓相册的一个路径问题,我是在相册路径下,新建了一个名叫ARphoto相册,所有保存下来的图片都保存在这个相册中,可以再图库应用中查看到这个相册文件夹。


在IOS端保存相册是无法单独在Unity中完成的。需要调用Xcode中的方法,关于Unity与Xcode之间的交互有什么疑问的可以查看我之前写的 博文http://blog.csdn.net/hasion/article/details/43668229

其具体实现方法如下:

public class TakePhoto : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void _SavePhoto (string readaddr);


private string path_save;
private string path_read;
public GameObject _demoBtns;

void OnClick ()
{
this.GetComponentInChildren<UITexture> ().enabled = false;
_demoBtns.SetActive (false);


System.DateTime now = System.DateTime.Now;
string filename = string.Format ("image{0}{1}{2}{3}{4}{5}.png", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
path_save = filename;
path_read = Application.persistentDataPath + "/" + path_save;

//set photomanager.cs
if (!string.IsNullOrEmpty (path_save)) {
PhotosManager.GetInstance ().PhotoPath = path_read;
}


StartCoroutine (SavePhoto ());
}


IEnumerator SavePhoto ()
{
yield return new WaitForSeconds (0.2f);
Application.CaptureScreenshot (path_save);
yield return new WaitForSeconds (0.5f);
this.GetComponentInChildren<UITexture> ().enabled = true;
_demoBtns.SetActive (true);


yield return new WaitForSeconds (1.2f);
_SavePhoto (path_read);


}
}

Xcode中执行文件如下:

#import "PhotoManager.h"
@implementation PhotoManager
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
          contextInfo: ( void *) contextInfo
{
    if (error != nil)
    {
        NSLog(@"有错误");
    }
    else
    {
        NSLog(@"保存结束");
    }
}


void _SavePhoto(char *readAddr)
{
    NSString *strReadAddr = [NSString stringWithUTF8String:readAddr];
    UIImage *img = [UIImage imageWithContentsOfFile:strReadAddr];
    NSLog(@"%@",[NSString stringWithFormat:@"w:%f, h:%f", img.size.width, img.size.height]);
    NSLog(@"%@",[NSString stringWithFormat:@"%s",readAddr ]);
    PhotoManager *instance = [PhotoManager alloc];
    UIImageWriteToSavedPhotosAlbum(img, instance,
                                   @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil);
}


@end


大体执行流程就是这样的,有什么错误或者建议的地方,欢迎大家指正,谢谢!!!





关于Unity中的Update、Lateupdate和FixedUpdate。
MonoBehaviour.Update更新当MonoBehaviour启用时,其Update在每一帧被调用。MonoBehaviour.FixedUpdate固定更新当MonoBehaviour启用时,其FixedUpdate在每一帧被调用。处理Rigi

Unity3D时间顺序与功能
Unity3D中所有控制脚本的基类MonoBehaviour有一些虚函数用于绘制中事件的回调,也可以直接理解为事件函数,例如大家都很清楚的Start,Update等函数,以下做

Unity+Mono断点调试步骤
项目制作过程中,我们可能要用到断点调试来检测程序运行过程中的实时数据,从而检测出程序出错的位置。具体步骤如下:1、Mono必须是Unity安装时自

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多