C# 이미지를 다운로드하고 저장하는 방법 (download image from url and save)

C#에서 이미지를 다운로드하고 저장해 보도록 하겠습니다. 예시 자료에서는 특정 이미지 파일 경로를 입력하여 바탕화면에 다운로드 받아보도록 할게요.

download image

다음 코드는 WPF 애플리케이션을 사용하여 이미지를 다운로드하고 바탕화면에 저장하는 예제입니다. 기본적으로 HttpWebRequest와 FileStream을 사용하여 이미지를 다운로드하고 저장합니다.

C# 이미지를 다운로드하고 저장하는 방법

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Media;

namespace BeomDownloadImage.View
{
    /// <summary>
    /// DownloadImageBeomSang.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class DownloadImageBeomSang : Window
    {
        public DownloadImageBeomSang()
        {
            InitializeComponent();

            txtURL.Text = "https://blogger.googleusercontent.com/img/a/AVvXsEh7RKSppEx53j-z1k8xkLhT-Tu79cDmg1KHKrJm7lnEuGORhXSuVm9rjLu8svYsF9Ooqj_-VZ2QBgRoFL4xzv2J-cDghhNLjG7cx0mqwzd6wuqwuVxVO84z7jmlHQwM_-yTvbKyJPIzOiEfh1iVuM3p2JgqF7DP1CbVGELg7I8nGadYx_FNy60XKNsY95e_";
            txtFileName.Text = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\\download_beomsang.png";
        }

        private bool DownloadImage(string _sourceUri, string _targetPath, ref string _contentType)
        {
            try
            {
                const int BUFFER_SIZE = 100 * 1024;
                bool rtn = false;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_sourceUri);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
                    {
                        _contentType = response.ContentType;
                        if (response.StatusCode == HttpStatusCode.OK ||
                            response.StatusCode == HttpStatusCode.Moved ||
                            response.StatusCode == HttpStatusCode.Redirect)
                        {
                            using (Stream stream = response.GetResponseStream())
                            {
                                using (Stream fileStream = new FileStream(_targetPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                                {
                                    byte[] buffer = new byte[BUFFER_SIZE];
                                    int bytesRead;
                                    do
                                    {
                                        bytesRead = stream.Read(buffer, 0, BUFFER_SIZE);
                                        fileStream.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                    rtn = true;
                                }
                            }
                        }
                        else
                        {
                            throw new Exception($"StatusCode is an unexpected value : {response.StatusCode}");
                        }
                    }
                    else
                    {
                        throw new Exception($"ContentType is not an image : {response.ContentType}");
                    }
                }
                return rtn;
            }
            catch (Exception ex)
            {
                txtResult.Text = ex.Message;
                return false;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            txtResult.Foreground = Brushes.Black;
            txtResult.Text = string.Empty;

            string url = txtURL.Text;
            string fileName = txtFileName.Text;
            string contentType = "?";
            if (DownloadImage(url, fileName, ref contentType))
            {
                txtResult.Foreground = Brushes.Blue;
                txtResult.Text = string.Format("Succes : URL={0}, FileName={1}, ContentType={2}", url, fileName, contentType);
            }
            else
            {
                txtResult.Foreground = Brushes.Red;
                txtResult.Text = string.Format("Failed : URL={0}, FileName={1}, ContentType={2}", url, fileName, contentType);
            }
        }
    }
}

주요 참고 사항

  1. 기본 설정: txtURL.TexttxtFileName.Text는 각각 다운로드할 이미지의 URL과 저장할 경로를 설정합니다.

  2. DownloadImage 메서드:

    • 이미지를 다운로드하기 위해 HttpWebRequest를 사용합니다.
    • 응답을 확인하여 이미지인지 확인하고, 상태 코드가 적절한지 확인합니다.
    • 이미지 데이터를 버퍼에 읽어 들여 파일에 씁니다.
  3. 버튼 클릭 이벤트:

    • 버튼을 클릭하면 Button_Click 메서드가 호출되어 이미지 다운로드를 시도합니다.
    • 다운로드 성공 여부에 따라 메시지를 업데이트합니다.

사용법

  1. URL과 파일명 설정: txtURLtxtFileName 텍스트 박스에 다운로드할 이미지의 URL과 저장할 파일 경로를 입력합니다.
  2. 버튼 클릭: 버튼을 클릭하여 다운로드를 시작합니다.
  3. 결과 확인: 결과 메시지로 다운로드 성공 또는 실패 여부를 확인할 수 있습니다.

실제로 사용해보면서 필요한 부분을 수정하거나 추가 기능을 구현해보세요.

댓글 쓰기
가져가실 때, 출처 표시 부탁드려요! 감사합니다. 💗