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:
Genel değişken tanımlaması için Form1 sınıfı içine aşağıdaki değişkenleri eklemeyi unutmayın.
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.
btnSave: Butona tıklandığında bilgisayarın D sürücüsüne txt formatında kaydetmek için gerekli kodları yazıyoruz.
Kodların tamamı:
Ekran:
Genel değişken tanımlaması için Form1 sınıfı içine aşağıdaki değişkenleri eklemeyi unutmayın.
C#:
public partial class Form1 : Form
{
Bitmap image; //eklenecek kod
string base64Text; //eklenecek kod
C#:
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;
}
C#:
string path = @"D:\sample\base64.txt";
using (StreamWriter stream= File.CreateText(path))
{
// stream.Write(richTextBox1.Text);
stream.Write(base64Text);
}
C#:
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);
}
}
}