Unity保存图片到相册

Unity保存图片到Android相册

Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

package com.xuefei.game;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import com.unity3d.player.UnityPlayerNativeActivity;

import android.content.Context;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.util.Log;

import android.widget.Toast;

public class MainActivity extends UnityPlayerNativeActivity {

    public static Context context;

    public static MainActivity mainActivity;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mainActivity = this;

    }

    // 保存到相册

    public static void savePng(final String fileName) {

        context = mainActivity.getApplicationContext();

        mainActivity.runOnUiThread(new Runnable() {

            public void run() {

                Bitmap bitmap = BitmapFactory.decodeFile(Environment

                        .getExternalStorageDirectory()

                        + "/Android/data/com.xuefei.game/files/"

                        + fileName

                        + ".png");

                File file = new File(Environment.getExternalStorageDirectory()

                        + "/DCIM/Camera", fileName + ".jpg");

                FileOutputStream fos = null;

                try {

                    fos = new FileOutputStream(file);

                } catch (FileNotFoundException e) {

                    // TODO Auto-generated catch block

                    Log.w("cat", e.toString());

                }

                bitmap.compress(CompressFormat.JPEG, 100, fos);

                try {

                    fos.flush();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    Log.w("cat", e.toString());

                }

                try {

                    fos.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    Log.w("cat", e.toString());

                }

                bitmap.recycle();//扫描保存的图片

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" +Environment.getExternalStorageDirectory()

                        + "/DCIM/Camera/"+fileName + ".jpg")));

                 

                Toast.makeText(context, "照片已保存到相册", Toast.LENGTH_SHORT).show();

  

            }

        });

    }

}



Unity中代码:

[C#] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

if (GUI.Button(new Rect(0, 720, 400, 120), "SavePng"))

        {

            StartCoroutine(SavePngToSD(DateTime.Now.ToFileTime().ToString()));

        }

/// <summary>

    /// 截图后先检测图片是否保存成功然后调用保存到相册

    /// </summary>

    /// <param name="name"></param>

    public void SavePng(string name)

    {

#if UNITY_ANDROID

        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");

        jo.CallStatic("SavePng", name);

#elif  UNITY_IPHONE

#endif

    }

/// <summary>

    /// 保存截图到相册

    /// </summary>

    /// <param name="pngName"></param>

    /// <returns></returns>

    IEnumerator SavePngToSD(string pngName)

    {

        yield return new WaitForEndOfFrame();

        Application.CaptureScreenshot(pngName + ".png");

        while (!IsFileExistByPath(Application.persistentDataPath + "/" + pngName + ".png"))

        {

            yield return new WaitForSeconds(0.05f);

        }

        SavePng(pngName);

        yield return new WaitForSeconds(0.3f);

        //测试请求文件

        WWW www = new WWW("file:///" + Application.persistentDataPath + "/" + pngName + ".png");

        yield return www;

    }

    /// <summary>

    /// 检测文件是否存在

    /// </summary>

    /// <param name="path"></param>

    /// <returns></returns>

    public static bool IsFileExistByPath(string path)

    {

        FileInfo info = new FileInfo(path);

        bool b = false;

        if (info == null || info.Exists == false)

        {

            b = false;

        }

        else

        {

            b = true;

        }

        return b;

    }


注意文件路径是否存在,不存在就创建


流程:Unity截屏--调用安卓拷贝到相册--扫描保存的文件

解决的问题:截屏图片在相册不显示。

Unity截屏插入iOS相册 

[C#] 纯文本查看 复制代码

?

 

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

using System;

using System.IO;

 

#if UNITY_IOS

using System.Runtime.InteropServices;

#endif

 

using UnityEngine;

 

public class UnityPlugins : MonoBehaviour

{

 

    // Use this for initialization

    void Start()

    {

 

    }

 

    // Update is called once per frame

    void Update()

    {

 

    }

 

    #if UNITY_IOS

    [DllImport("__Internal")]

    private static extern void _SavePhoto(string readAddr);

    #endif

 

    string path = "";

 

    private void OnGUI()

    {

 

        if (GUILayout.Button("TakePhoto", GUILayout.Height(300), GUILayout.Width(300)))

        {

            CaptureCamera();

            Debug.Log("TakePhoto");

        

    }

 

 

    void CaptureCamera()

    {

        Camera camera = Camera.main;

        string name = DateTime.Now.ToFileTime().ToString();

 

        Rect rect = new Rect(0, 0, Screen.width, Screen.height);

 

        RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 0);

        Texture2D frame = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);

 

        camera.targetTexture = rt;

        camera.Render();

 

        RenderTexture.active = rt;

        frame.ReadPixels(rect, 0, 0);

        frame.Apply();

 

        camera.targetTexture = null

        RenderTexture.active = null;  

 

        byte [] bytes = frame.EncodeToJPG();

 

        File.WriteAllBytes(Application.persistentDataPath + "/" + name + ".jpg",bytes);

 

        #if UNITY_IOS

        _SavePhoto(Application.persistentDataPath + "/" + name + ".jpg");

        #endif

    }

 

}




iOS代码

[AppleScript] 纯文本查看 复制代码

?

 

1

2

3

4

5

#import <Foundation/Foundation.h> 

    

@interface UnityPlugins : NSObject 

- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error  

    contextInfo: ( void *) contextInfo; 

@end



 

[AppleScript] 纯文本查看 复制代码

?

 

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

#import "UnityPlugins.h" 

@implementation UnityPlugins 

- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error  

    contextInfo: ( void *) contextInfo 

{ 

    NSLog(@"保存结束")

    if (error != nil) { 

        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])

    UnityPlugins *instance = [UnityPlugins alloc]; 

    UIImageWriteToSavedPhotosAlbum(img, instance,  

        @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil)

} 

@end




目录结构
 


导出Xcode工程后或者  修改Info.plist  打开 Info.plist,点击 + 号,在 Key 中输入:Privacy - Photo Library Additions Usage Description,Type 选择 String,Value 中输入你的提示语(比如XXX访问相册)再次 Build

猜你喜欢

转载自blog.csdn.net/Game_jqd/article/details/82056220