프로그래밍/C#
[C#] 웹 파일 MemoryStream/base64 변환 ,웹 파일 이미지 크기 변환 (Web File to Stream/base64/WebClient)
in4obank
2023. 6. 26. 16:08
오늘은 WebClient를 활용용하여 웹 파일 MemoryStream 변환,base64변환.
MemoryStream형식의 이미지 크기 변환하는 방법에 대해 알아보겠습니다.
1. using 추가
using System;
using System.Drawing;
using System.IO;
using System.Net;
2. 예제
using System;
using System.Drawing;
using System.IO;
using System.Net;
public class Program
{
public static MemoryStream convertStream(string fileUrl)
{
MemoryStream ms;
using (WebClient client = new WebClient())
{
byte[] fileBytes = client.DownloadData(fileUrl);
ms = new MemoryStream(fileBytes);
}
return ms;
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight) // 이미지 resize
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
public static MemoryStream resizeImage(MemoryStream stream)
{
Image img = Image.FromStream(stream);
int width = img.Width;
int height = img.Height;
if(width > 1296)
{
width = 1269; // width 최대값 지정
}
if(height > 800)
{
height = 800; // height 최대값 지정
}
Image thumb = ScaleImage(img, width, height);
stream = new MemoryStream();
thumb.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
return stream;
}
public static void Main()
{
string fileUrl = @"https://code.jquery.com/jquery-3.6.1.min.js";
string imgUrl = @"이미지 url";
MemoryStream cms = convertStream(fileUrl); // File -> MemoryStream 변환
string Base64Txt = Convert.ToBase64String(cms.ToArray()); // File -> base64 변환
Image resizeImg = Image.FromStream(resizeImage(cms)); // File -> resizeImage
}
}
위의 소스 코드를 응용하여 저장 시/ 웹에 다시 보여줄떄 이미지 resize가 가능하고 다운로드 받은 파일을 다시 stream 형식으로 전송도 가능합니다.
감사합니다.
반응형