unity 截图/图片保存到手机相册

从unity保存图片到相册,游戏中需要一些保存图片到相册的操作。

===unity 这边的C# 代码====

#if UNITY_IPHONE     //与调用ios 里面的保存相册接口
    [DllImport("__Internal")]
    private static extern void SavePhotoAlubm(string path);
#endif



//传的参数是自己获取的图片 

public IEnumerator getTexture2d(Texture2D t)

    {
        //截图操作  



        yield return new WaitForEndOfFrame();

        //截图保存的图片

        //Texture2D t = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);



        //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);
        //应用平台判断,路径选择  
        if (Application.platform == RuntimePlatform.Android)
        {
            string origin = Path_save;
            destination = "/mnt/sdcard/DCIM/Screenshots";
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            destination = destination + "/" + filename;
            Path_save = destination;
            //保存文件  
            Debug.Log("路径:" + Path_save);


            File.WriteAllBytes(Path_save, bytes);

            // 安卓在这里需要去 调用原生的接口去 刷新一下,不然相册显示不出来

             using (AndroidJavaClass playerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
          {
              using (AndroidJavaObject jo = playerActivity.GetStatic("currentActivity"))
              {
                     Debug.Log("scanFile:m_androidJavaObject " );
                      jo.Call("scanFile",Path_save);
                }
           }
         }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            string origin = Path_save;
            destination = Application.persistentDataPath;
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            destination = destination + "/" + filename;
            Path_save = destination;
            //保存文件    ios需要在本地保存文件后,然后将保存的图片的路径 传给ios 
            Debug.Log("路径:" + Path_save);
            File.WriteAllBytes(Path_save, bytes);
            SavePhotoAlubm(Path_save);
        }



    }

==== 安卓 jar端 =====

//安卓端接受 刷新相册的接口

 public void scanFile(String filePath) {
  Log.i("Unity", "------------filePath"+filePath); 
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(new File(filePath)));
this.sendBroadcast(scanIntent);  //我这边 this 是UnityPlayerActivity
}

====ios端 保存相册====

.h 文件如下

#import 
@interface IOSAlbumCameraManager :NSObject
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
          contextInfo: ( void *) contextInfo;
+(instancetype)sharedManager;
-(void) savePhotoAlbum:(NSString*) readAddr;

@end

.mm文件如下

#import "IOSAlbumCameraManager.h"
@implementation IOSAlbumCameraManager
+(instancetype)sharedManager
{
    static dispatch_once_t onceToken;
    static IOSAlbumCameraManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[IOSAlbumCameraManager alloc] init];
    });
    return instance;
}

- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
          contextInfo: ( void *) contextInfo
{
    if(error)
    {
        NSLog(@"图片保存到相册失败!");
    }
    else
    {
        NSLog(@"图片保存到相册成功!");
    }
}
-(void) savePhotoAlbum:(NSString*) readAddr
{
    UIImage *img = [UIImage imageWithContentsOfFile:readAddr];
    NSLog([NSString stringWithFormat:@"w:%f, h:%f", img.size.width, img.size.height]);
    //IOSAlbumCameraManager *instance = [IOSAlbumCameraManager alloc];
    UIImageWriteToSavedPhotosAlbum(img, self,
                                   @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil);
}

如果有不懂的或者更好的方法欢迎在下方留言。

你可能感兴趣的:(unity3d)