using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace AGVNavigationCore.Utils
{
///
/// 이미지와 문자열 간 변환을 위한 유틸리티 클래스
/// Base64 인코딩을 사용하여 이미지를 문자열로 변환하거나 그 반대로 수행
///
public static class ImageConverterUtil
{
///
/// Image 객체를 Base64 문자열로 변환
///
/// 변환할 이미지
/// 이미지 포맷 (기본값: PNG)
/// Base64 인코딩된 문자열, null인 경우 빈 문자열 반환
public static string ImageToBase64(Image image, ImageFormat format = null)
{
if (image == null)
return string.Empty;
try
{
format = format ?? ImageFormat.Png;
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, format);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"이미지 변환 실패: {ex.Message}");
return string.Empty;
}
}
///
/// 파일 경로의 이미지를 Base64 문자열로 변환
///
/// 이미지 파일 경로
/// 변환할 포맷 (기본값: PNG, 원본 포맷 유지하려면 null)
/// Base64 인코딩된 문자열
public static string FileToBase64(string filePath, ImageFormat format = null)
{
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
return string.Empty;
try
{
using (var image = Image.FromFile(filePath))
{
return ImageToBase64(image, format ?? ImageFormat.Png);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"파일 변환 실패: {ex.Message}");
return string.Empty;
}
}
///
/// Base64 문자열을 Image 객체로 변환
///
/// Base64 인코딩된 문자열
/// 변환된 Image 객체, 실패 시 null
public static Image Base64ToImage(string base64String)
{
if (string.IsNullOrEmpty(base64String))
return null;
try
{
byte[] imageBytes = Convert.FromBase64String(base64String);
using (var memoryStream = new MemoryStream(imageBytes))
{
return Image.FromStream(memoryStream);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Base64 이미지 변환 실패: {ex.Message}");
return null;
}
}
///
/// Base64 문자열을 Bitmap 객체로 변환
/// Image 대신 Bitmap을 반환하므로 메모리 관리가 더 안정적
///
/// Base64 인코딩된 문자열
/// 변환된 Bitmap 객체, 실패 시 null
public static Bitmap Base64ToBitmap(string base64String)
{
if (string.IsNullOrEmpty(base64String))
return null;
try
{
byte[] imageBytes = Convert.FromBase64String(base64String);
using (var memoryStream = new MemoryStream(imageBytes))
{
return new Bitmap(memoryStream);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Base64 Bitmap 변환 실패: {ex.Message}");
return null;
}
}
///
/// Base64 문자열이 유효한지 확인
///
/// 검증할 Base64 문자열
/// 유효하면 true, 그 외 false
public static bool IsValidBase64(string base64String)
{
if (string.IsNullOrWhiteSpace(base64String))
return false;
try
{
Convert.FromBase64String(base64String);
return true;
}
catch
{
return false;
}
}
///
/// Base64 이미지 데이터의 크기를 대략적으로 계산 (바이트 단위)
///
/// Base64 문자열
/// 예상 바이트 크기
public static long GetApproximateSize(string base64String)
{
if (string.IsNullOrEmpty(base64String))
return 0;
// Base64는 원본 데이터보다 약 33% 더 큼
return (long)(base64String.Length * 0.75);
}
}
}