首先说一下安卓:首先在相册里创建一个文件,然后将图片存入。
代码:
using UnityEngine;
using System.Collections;
using System.IO;
public class SavaPicture : MonoBehaviour {
// Use this for initialization
void Start () {
//保存图片
StartCoroutine(LoadImg());
}
IEnumerator LoadImg()
{
WWW www = new WWW("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498635837686&di=cc15b088c3c1376d724891abd74736b1&imgtype=0&src=http%3A%2F%2Fk2.jsqq.net%2Fuploads%2Fallimg%2F1705%2F7_170524143440_5.jpg");
yield return www;
Texture2D texture2D = www.texture;
byte[] bytes = texture2D.EncodeToPNG();
string fileName = "二维码.png";
string path;
//安卓平台
else if (Application.platform == RuntimePlatform.Android)
{
string destination = "/sdcard/DCIM/棋牌";
//判断目录是否存在,不存在则会创建目录
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
path = destination + "/" + fileName;
//存图片
System.IO.File.WriteAllBytes(path, bytes);
}
//电脑端
else
{
path = Application.dataPath + "/" + fileName;
FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
}
Debug.Log(path);
}
}
需要注意的是:打包的时候 配置一下:player Settings---->other Settings------>write Access------>External(SDCard)
下面说一下苹果:
PhotoManager.h 文件内容
#import <Foundation/Foundation.h>
@interface PhotoManager : NSObject
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
contextInfo: ( void *) contextInfo;
@end
PhotoManager.mm 文件 内容如下
#import "PhotoManager.h"
@implementation PhotoManager
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
contextInfo: ( void *) contextInfo
{
NSLog(@"保存结束");
if (error != nil) {
NSLog(@"有错误");
}
}
@end
extern "C" {
void _SavePhoto(char *readAddr)
{
NSString *strReadAddr = [NSString stringWithUTF8String:readAddr];
UIImage *img = [UIImage imageWithContentsOfFile:strReadAddr];
PhotoManager *instance = [PhotoManager alloc];
UIImageWriteToSavedPhotosAlbum(img, instance,
@selector(imageSaved:didFinishSavingWithError:contextInfo:), nil);
}
}
需要注意:苹果打包的时候 我们需要打开info.plist文件添加相应权限的说明,否则程序在iOS10上会出现崩溃。或则打包出现错误。
添加相册权限:
相册权限: Privacy - Photo Library Usage Description 是否允许此App访问你的媒体资料库?
Unity 项目DEMO 点击打开链接