Unity中生成相机照片并保存到本地的详细教程


前言

在游戏和应用程序开发中,有时候需要通过代码在Unity中使用相机捕捉当前场景或特定视角的照片,并将其保存到本地。本教程将演示如何通过C#代码实现这一功能。


一、代码基本结构

 /// <summary>
    /// 生成相机照片并保存
    /// </summary>
    /// <param name="photographyCamera">相机</param>
    /// <param name="width">图像宽度</param>
    /// <param name="height">图像高度</param>
    /// <param name="path">保存路径</param>
    /// <param name="imageName">保存图片名字</param>
    public void CreateCameraCaptureAndSaveLocal(Camera photographyCamera,int width,int height, string path, string imageName){
        // 销毁之前的 RenderTexture 和 Texture2D
        if (photographyCamera.targetTexture != null){
            RenderTexture.ReleaseTemporary(photographyCamera.targetTexture);
            photographyCamera.targetTexture = null;
            RenderTexture.active = null;
        }

        // 创建 RenderTexture
        RenderTexture rt = new RenderTexture(width, height, 16, RenderTextureFormat.ARGB32);
        photographyCamera.targetTexture = rt;
        GL.Clear(true, true, Color.clear); // 清除颜色和深度缓冲区
        photographyCamera.Render();
        RenderTexture.active = rt;

        // 创建 Texture2D 并读取图像数据
        Texture2D image = new Texture2D(width, height, TextureFormat.ARGB32, false);
        image.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        image.Apply();

        // 重要:将 targetTexture 设置为 null,以便相机继续渲染到主屏幕
        photographyCamera.targetTexture = null;
        RenderTexture.active = null;

        // 检查保存路径是否为空或无效
        if (string.IsNullOrEmpty(path)){
            Debug.LogError("Invalid save path.");
            return;
        }

        // 如果文件夹不存在,则创建文件夹
        if (!Directory.Exists(path)){
            Directory.CreateDirectory(path);
        }

        // 保存图像到本地文件夹

        byte[] bytes = image.EncodeToJPG();
        if (bytes != null){
            string savePath = Path.Combine(path, imageName + ".jpg");

            try{
                File.WriteAllBytes(savePath, bytes);
                Debug.Log("Image saved successfully: " + savePath);
            }
            catch (Exception e){
                Debug.LogError("Error saving image: " + e.Message);
            }
        }
        else{
            Debug.LogError("Failed to encode image to JPG.");
        }
    }

二、使用步骤

1. 函数定义

/// <summary>
/// 生成相机照片并保存
/// </summary>
/// <param name="photographyCamera">相机</param>
/// <param name="width">图像宽度</param>
/// <param name="height">图像高度</param>
/// <param name="path">保存路径</param>
/// <param name="imageName">保存图片名字</param>
public void CreateCameraCaptureAndSaveLocal(Camera photographyCamera, int width, int height, string path, string imageName){

此函数的目标是使用给定的相机(photographyCamera)生成图像,并将图像保存到指定路径。函数有五个参数,分别是相机、图像宽度、图像高度、保存路径和保存图片的名字

2. 销毁之前的 RenderTexture 和 Texture2D

// 销毁之前的 RenderTexture 和 Texture2D
if (photographyCamera.targetTexture != null){
    RenderTexture.ReleaseTemporary(photographyCamera.targetTexture);
    photographyCamera.targetTexture = null;
    RenderTexture.active = null;
}

此段代码确保在生成新图像前,释放之前的渲染纹理和2D纹理,以防止内存泄漏。

3. 创建 RenderTexture

// 创建 RenderTexture
RenderTexture rt = new RenderTexture(width, height, 16, RenderTextureFormat.ARGB32);
photographyCamera.targetTexture = rt;
GL.Clear(true, true, Color.clear); // 清除颜色和深度缓冲区,防止图像叠加
photographyCamera.Render();
RenderTexture.active = rt;

在这里,我们创建了一个新的RenderTexture(rt),用于保存相机渲染的图像。相机的目标渲染纹理被设置为这个新创建的纹理,然后相机被渲染,将图像绘制到rt上。

4. 创建 Texture2D 并读取图像数据

// 创建 Texture2D 并读取图像数据
Texture2D image = new Texture2D(width, height, TextureFormat.ARGB32, false);
image.ReadPixels(new Rect(0, 0, width, height), 0, 0);
image.Apply();


在这一步,我们创建了一个新的Texture2D(image),并使用ReadPixels方法从RenderTexture中读取像素数据。Apply方法确保纹理被正确应用。

5. 重要步骤:设置 targetTexture 为 null

// 重要:将 targetTexture 设置为 null,以便相机继续渲染到主屏幕
photographyCamera.targetTexture = null;
RenderTexture.active = null;


这一步非常重要,因为它将相机的目标渲染纹理设置为null,以确保相机继续在主屏幕上渲染。这是在生成图像后必须执行的步骤。

6. 检查保存路径是否有效

// 检查保存路径是否为空或无效
if (string.IsNullOrEmpty(path)){
    Debug.LogError("Invalid save path.");
    return;
}

// 如果文件夹不存在,则创建文件夹
if (!Directory.Exists(path)){
    Directory.CreateDirectory(path);
}

在这里,我们检查用户提供的保存路径是否为空或无效。如果路径无效,将打印错误消息并提前返回,避免后续操作导致错误。
如果保存路径对应的文件夹不存在,我们会创建这个文件夹。这样可以确保保存图像的目标路径是有效的。

7. 保存图像到本地文件夹

// 保存图像到本地文件夹
byte[] bytes = image.EncodeToJPG();
if (bytes != null){
    string savePath = Path.Combine(path, imageName + ".jpg");

    try{
        File.WriteAllBytes(savePath, bytes);
        Debug.Log("Image saved successfully: " + savePath);
    }
    catch (Exception e){
        Debug.LogError("Error saving image: " + e.Message);
    }

    // 保存文件路径到特定键值
    _rc.WriteKey("takingPhotosPath", savePath);
}
else{
    Debug.LogError("Failed to encode image to JPG.");
}


在这里,我们将Texture2D中的图像数据编码为JPG格式的字节数组,并将其写入指定路径的文件中。如果保存成功,将打印成功消息并将文件路径保存到特定的键值。如果保存失败,将打印错误消息。


总结

通过这个函数,你可以在游戏开发中轻松实现相机捕捉和图像保存的功能,方便用于创建截图、快照等场景。

  • 34
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Unity实现手机相机拍照并保存,首先需要使用Unity的调用手机相机的API。我们可以通过Unity的Input类的GetButtonDown函数来捕捉到手机相机按钮被按下的事件。 首先,我们需要在Unity创建一个按钮对象用来触发拍照的操作。然后,在按钮的脚本,我们可以编写如下代码: ``` using UnityEngine; using System.Collections; using System.IO; public class CameraController : MonoBehaviour { // 定义保存图片的路径和文件名 private string savePath = "/sdcard/DCIM/Camera/"; private string fileName = "photo.png"; // 第一次触发拍照按钮时调用 void OnMouseDown() { StartCoroutine(TakeAndSavePhoto()); } // 拍照并保存的协程函数 IEnumerator TakeAndSavePhoto() { // 调用手机相机 yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); if (Application.HasUserAuthorization(UserAuthorization.WebCam)) { WebCamTexture webcamTexture = new WebCamTexture(); webcamTexture.Play(); // 拍照 yield return new WaitForEndOfFrame(); Texture2D photo = new Texture2D(webcamTexture.width, webcamTexture.height); photo.SetPixels(webcamTexture.GetPixels()); photo.Apply(); // 保存照片 byte[] bytes = photo.EncodeToPNG(); File.WriteAllBytes(savePath + fileName, bytes); Debug.Log("照片保存至:" + savePath + fileName); // 停止相机 webcamTexture.Stop(); } } } ``` 以上的代码使用了Unity的协程函数来实现拍照和保存照片的操作。首先,我们使用Application.RequestUserAuthorization函数请求用户授权使用相机。如果授权成功,我们创建一个WebCamTexture对象并将其作为相机预览。 当按钮被按下后,我们调用WebCamTexture.GetPixels函数获取相机的当前帧数据并创建一个新的Texture2D对象用来保存照片。然后,我们使用Texture2D.EncodeToPNG函数将照片转换为PNG格式并使用File.WriteAllBytes函数将照片保存到指定路径。 最后,我们通过调用WebCamTexture.Stop函数停止相机预览。 在代码,我们将照片保存到了"/sdcard/DCIM/Camera/"路径下的"photo.png"文件。你可以根据你的实际需求修改保存路径和文件名。 希望以上内容对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨染青枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值