将图像(按路径选择)转换为 base64 字符串 [英] Convert an image (selected by path) to base64 string

查看:32
本文介绍了将图像(按路径选择)转换为 base64 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图像从用户计算机上的路径转换为 ​​C# 中的 base64 字符串?

How do you convert an image from a path on the user's computer to a base64 string in C#?

例如,我有图像的路径(格式为 C:/image/1.gif),并且想要一个像 data:image/gif 这样的数据 URI;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. 表示返回的 1.gif 图像.

For example, I have the path to the image (in the format C:/image/1.gif) and would like to have a data URI like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. representing the 1.gif image returned.

推荐答案

获取图像的字节数组(byte[])表示,然后使用Convert.ToBase64String()代码>,圣.像这样:

Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:

byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);

要将 base64 图像转换回 System.Drawing.Image:

To convert a base64 image back to a System.Drawing.Image:

var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));

这篇关于将图像(按路径选择)转换为 base64 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆