C# Resim Dosyalarını Base64String’e Çevirme

sdkbyrm

webmasterfrm
Üyelik Tarihi
23 Aralık 2020
Mesajlar
813
Beğeniler
1
Ticaret: 0 / 0 / 0
Bu yazıda bir resim dosyasını base64 formatında nasıl kaydedeceğinizi göstereceğim. Öncelikle bu uygulamayı C# Windows Form uygulaması olarak oluşturdum. Aşağıdaki gibi bir form ekranını oluşturarak uygulamayı oluşturmaya başlayabilirsiniz.


Ekran:

Screenshot_2.png




Genel değişken tanımlaması için Form1 sınıfı içine aşağıdaki değişkenleri eklemeyi unutmayın.


1
2
3
4
5
6
7
8

public partial class Form1 : Form
{
Bitmap image; //eklenecek kod
string base64Text; //eklenecek kod
.......
.......


btnOpen: Yukarıdaki formu oluşturduktan sonra btnOpen butonuna çift tıklayarak butonun click olayını açıp içene aşağıdaki kodları yazın.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG" +
"|All files(*.*)|*.*";
dialog.CheckFileExists = true;
dialog.Multiselect = false;
if(dialog.ShowDialog()==DialogResult.OK)
{
image = new Bitmap(dialog.FileName);
pictureBox1.Image = (Image)image;

byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName);
base64Text = Convert.ToBase64String(imageArray); //base64Text must be global but I'll use richtext
richTextBox1.Text = base64Text;
}
btnSave: Butona tıklandığında bilgisayarın D sürücüsüne txt formatında kaydetmek için gerekli kodları yazıyoruz.


1
2
3
4
5
6
7
8

string path = @"D:\sample\base64.txt";
using (StreamWriter stream= File.CreateText(path))
{
// stream.Write(richTextBox1.Text);
stream.Write(base64Text);
}


Kodların tamamı:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

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

namespace base64Example
{
public partial class Form1 : Form
{
Bitmap image;
string base64Text;
public Form1()
{
InitializeComponent();
}

private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG" +
"|All files(*.*)|*.*";
dialog.CheckFileExists = true;
dialog.Multiselect = false;
if(dialog.ShowDialog()==DialogResult.OK)
{
image = new Bitmap(dialog.FileName);
pictureBox1.Image = (Image)image;

byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName);
base64Text = Convert.ToBase64String(imageArray); //base64Text must be global but I'll use richtext
richTextBox1.Text = base64Text;
}
}

private void btnSave_Click(object sender, EventArgs e)
{
string path = @"D:\sample\base64.txt";
using (StreamWriter stream= File.CreateText(path))
{
// stream.Write(richTextBox1.Text);
stream.Write(base64Text);
}
}
}
}


Ekran Çıktısı:

Screenshot_1.png
 
Üst