Files
CopyAndEncodeImage/Form1.cs

49 lines
2.0 KiB
C#

using System;
using System.IO;
using System.Windows.Forms;
namespace CopyAndEncodeImage {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btnEncode_Click(object sender, EventArgs e) {
if (!File.Exists(textBox1.Text)) {
MessageBox.Show("The specified file does not exist.", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (Path.GetExtension(textBox1.Text).ToLower() != ".png") {
MessageBox.Show("Please select a valid PNG file.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try {
byte[] bytes = File.ReadAllBytes(textBox1.Text);
string base64String = Convert.ToBase64String(bytes);
string output = $"data:image/png;base64,{base64String}";
Clipboard.SetText(output);
MessageBox.Show("Image encoded and copied to clipboard successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
} catch (Exception ex) {
MessageBox.Show($"An error occurred while encoding the image: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnChoose_Click(object sender, EventArgs e) {
OpenFileDialog openFileDialog = new OpenFileDialog {
Filter = "PNG Files|*.png",
Title = "Select a PNG Image",
FileName = string.IsNullOrEmpty(textBox1.Text) ? "" : textBox1.Text
};
if (openFileDialog.ShowDialog() == DialogResult.OK) {
textBox1.Text = openFileDialog.FileName;
}
}
private void textBox1_TextChanged(object sender, EventArgs e) {
btnEncode.Enabled = !string.IsNullOrEmpty(textBox1.Text) && System.IO.Path.GetExtension(textBox1.Text).ToLower() == ".png";
}
}
}