Reputation: 193
I want to load an image and directly encode this to a base64 string. Small/low-res pictures load fast but loading a picture taken by an iPhone 5 for example (2448 x 3264, 2.61 MB) takes ages. Is there a way to load these images faster in my application?
Here is my C# code:
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//Setup OpenFileDialog
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string sFileName = openFileDialog1.FileName;
textBox1.Text = sFileName;
pictureBox1.ImageLocation = sFileName;
using (Bitmap bm = new Bitmap(sFileName))
{
using (var ms = new MemoryStream())
{
bm.Save(ms, ImageFormat.Jpeg);
base64 = Convert.ToBase64String(ms.ToArray());
textBox3.Text = base64;
}
}
}
}
}
}
Upvotes: 0
Views: 964
Reputation: 5558
Yes, the method you are using is probably the most popular I've seen out there. I needed to convert images too so I wrote something using that same method. However, it was simply too inefficient and slow for me. I decided to look for workarounds. I found this small program written in C by John Walker called base64.exe
. I made a wrapper around it with some modifications on the output.
The result is Base64encoder, but it was written relatively a long time ago. I've uploaded the source here: Base64encoder_v2.1-source.zip (released under MIT License)
I've later made a C library that can be found here: https://github.com/joedf/base64.c (released under MIT License)
You can either fork the wrapper or fork the c library into a c# library, or use some other library or write something from scratch... :/
Upvotes: 1
Reputation: 2191
It is recommended that you do not convert big sized images into Base64.. If you try to base64 larger images you will end up with a great deal of code in your html and lose out on the performance benefits...
Upvotes: 0