FirebaseStorageManager

그대처럼·2025년 1월 13일
0

규칙

rules_version = '2';

// Craft rules based on data in your Firestore database
// allow write: if firestore.get(
//    /databases/(default)/documents/users/$(request.auth.uid)).data.isAdmin;
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
       	allow read: if request.auth != null;
      	allow write: if request.auth != null;
    }
  }
}

코드

using Firebase.Storage;
using System;
using System.Threading.Tasks;
using Firebase.Auth;
using UnityEngine;
using UnityEngine.UI;

public class FirebaseStorageManager : MonoBehaviour
{
    //? 소스가 될 이미지
    public Sprite sprite;
    //? 소스를 출력할 이미지
    public Image m_Image;
    private FirebaseStorage storage;
    private StorageReference storageReference;
    
    private void Start()
    {
        // Firebase Storage 초기화
        storage = FirebaseStorage.DefaultInstance;
        storageReference = storage.RootReference;
    }

    /// <summary>
    /// 데이터를 Firebase Storage에 업로드합니다.
    /// </summary>
    /// <param name="key">저장 경로 키.</param>
    /// <param name="datas">업로드할 데이터 (byte 배열).</param>
    public async void SaveData(string key, byte[] datas)
    {
        if (datas == null || datas.Length == 0)
        {
            Debug.LogError("업로드할 데이터가 없습니다.");
            return;
        }

        try
        {
            // 지정된 키로 Firebase Storage 참조 생성
            StorageReference dataReference = storageReference.Child(key);

            // 데이터를 Firebase Storage에 업로드
            await dataReference.PutBytesAsync(datas);

            Debug.Log($"데이터가 성공적으로 업로드되었습니다: {key}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"데이터 업로드 실패: {ex.Message}");
        }
    }
    
    public void OnSendImage()
    {
        SaveData(FirebaseAuth.DefaultInstance.CurrentUser.UserId, SpriteToByteArray(sprite));
    }

    public async void OnLoadImage()
    {
        if (m_Image == null)
        {
            Debug.LogError("Image 컴포넌트가 설정되지 않았습니다.");
            return;
        }

        try
        {
            string userId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;

            // Firebase Storage에서 이미지 경로 지정
            StorageReference imageRef = storageReference.Child(userId);

            // 이미지 다운로드
            byte[] imageBytes = await imageRef.GetBytesAsync(5 * 1024 * 1024); // 최대 5MB

            if (imageBytes != null)
            {
                // byte[] 데이터를 Sprite로 변환
                Sprite sprite = ByteArrayToSprite(imageBytes);

                if (sprite != null)
                {
                    // Image 컴포넌트에 Sprite 적용
                    m_Image.sprite = sprite;
                    m_Image.SetNativeSize();
                    Debug.Log("이미지를 성공적으로 로드했습니다.");
                }
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"이미지 로드 실패: {ex.Message}");
        }
    }
    /// <summary>
    /// byte[] 데이터를 Sprite로 변환합니다.
    /// </summary>
    public static Sprite ByteArrayToSprite(byte[] byteArray)
    {
        if (byteArray == null || byteArray.Length == 0)
        {
            Debug.LogError("유효하지 않은 byte[] 데이터입니다.");
            return null;
        }

        try
        {
            // Texture2D 생성
            Texture2D texture = new Texture2D(2, 2);
            texture.LoadImage(byteArray); // byte[] 데이터를 Texture2D로 로드

            // Texture2D에서 Sprite 생성
            Sprite sprite = Sprite.Create(texture, 
                new Rect(0, 0, texture.width, texture.height), 
                new Vector2(0.5f, 0.5f)); // Pivot을 중심으로 설정

            return sprite;
        }
        catch (Exception ex)
        {
            Debug.LogError($"byte[]를 Sprite로 변환하는 중 오류 발생: {ex.Message}");
            return null;
        }
    }
    public static byte[] SpriteToByteArray(Sprite sprite)
    {
        if (sprite == null || sprite.texture == null)
        {
            Debug.LogError("유효하지 않은 Sprite입니다.");
            return null;
        }

        try
        {
            // Sprite의 Texture2D 가져오기
            Texture2D texture = sprite.texture;

            // Texture2D 데이터를 PNG 형식으로 변환
            byte[] byteArray = texture.EncodeToPNG();

            return byteArray;
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Sprite를 byte[]로 변환하는 중 오류 발생: {ex.Message}");
            return null;
        }
    }
}

0개의 댓글

관련 채용 정보