是否可以在 C# 中快速加载图像并将其编码为 base64?

Is it possible to load and encode images to base64 fast in C#?

我想加载一张图片并将其直接编码为 base64 字符串。 Small/low-res 图片加载速度很快,但加载 iPhone 5 拍摄的图片(2448 x 3264,2.61 MB)需要很长时间。有没有办法在我的应用程序中更快地加载这些图像?

这是我的 C# 代码:

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;
                        }
                    }
                }
            }
        }
    }

建议您不要将大尺寸图片转成Base64.. 如果您尝试对较大的图像进行 base64 编码,您最终会在 html 中添加大量代码,并失去性能优势...

参考文献 this & this.

是的,您使用的方法可能是我见过的最流行的方法。我也需要转换图像,所以我用同样的方法写了一些东西。 但是,它对我来说太低效和太慢了。我决定寻找解决方法。我发现了 John Walker called base64.exe 用 C 编写的这个小程序。我围绕它做了一个包装器,并对输出进行了一些修改。

结果是Base64encoder, but it was written relatively a long time ago. I've uploaded the source here: Base64encoder_v2.1-source.zip(在MIT许可证下发布)

我后来制作了一个 C 库,可以在这里找到:https://github.com/joedf/base64.c(根据 MIT 许可证发布)

您可以分叉包装器或将 c 库分叉到 c# 库中,或者使用其他库或从头开始编写一些东西...:/