본문 바로가기

C#/개발

[C#] 웹 이미지 다운로더

만들면서 이게 이렇게 간단하다고? 라는 생각이 들었다. WebClient의 DownloadFile 메소드를 이용하면 더 간단하게 구현할 수 있다. (대신 이미지 크기는 못 얻을 듯 하다)

 

C# 실력 늘리기 3일차의 지뢰게임 이미지를 다운로드

 

다운로드 경로에 저장된 지뢰게임 이미지 (test123.jpg)

 

코드

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Drawing.Imaging;
using System.IO;

namespace Webdownlaod
{
    public partial class Form1 : Form
    {
        WebFile wf;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            wf = new WebFile();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            string url = txtRead.Text;
            try
            {
                pictureBox1.Image = wf.DownloadBitmap(url);
            }
            catch (Exception) { MessageBox.Show("이미지를 읽어오는데 실패했습니다."); }
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            string url = txtRead.Text;
            string fname = txtSave.Text;
            try
            {
                Bitmap bit = wf.DownloadBitmap(url);
                MessageBox.Show(bit.Size.ToString());
                wf.SaveMemoryStream(bit, fname);
                MessageBox.Show("이미지 저장에 성공했습니다.");
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
        public class WebFile
        {
            public Bitmap DownloadBitmap(string url)
            {
                WebClient web = new WebClient();
                byte[] downs = web.DownloadData(url);
                Bitmap bit = null;
                using (MemoryStream ms = new MemoryStream(downs))
                {
                    bit = new Bitmap(ms);
                }
                return bit;
            }
            public void SaveMemoryStream(Bitmap bit, string fname)
            {
                MemoryStream ms = new MemoryStream();
                bit.Save(ms, ImageFormat.Bmp);
                using (FileStream outStream = File.OpenWrite(fname))
                {
                    ms.WriteTo(outStream);
                    outStream.Close();
                }
            }
        }
    }
}

'C# > 개발' 카테고리의 다른 글

[C#] RSA 암호화 & 복호화  (0) 2022.08.05
[C#] 로또  (0) 2022.08.05
[C#] 시리얼 통신과 장비조작  (0) 2022.08.05
[C#] 그래픽  (0) 2022.08.05
[C#] 계산기  (0) 2022.08.04