Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将图像(按路径选择)转换为base64字符串_C#_Image_Base64 - Fatal编程技术网

C# 将图像(按路径选择)转换为base64字符串

C# 将图像(按路径选择)转换为base64字符串,c#,image,base64,C#,Image,Base64,如何将图像从用户计算机上的路径转换为C#中的base64字符串 例如,我有图像的路径(格式为C:/image/1.gif),并且希望有一个类似data:image/gif的数据URI;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..表示返回的1.gif图像。获取图像的字节数组(byte[])表示,然后使用转换.ToBase64String(),如下: byte[] imageArray = System.IO.File.ReadAllBytes(@"image

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

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

获取图像的字节数组(
byte[]
)表示,然后使用
转换.ToBase64String()
,如下:

byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
要将base64映像转换回
System.Drawing.image

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

using (Image image = Image.FromFile(Path))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

这是我为此编写的课程:

public class Base64Image
{
    public static Base64Image Parse(string base64Content)
    {
        if (string.IsNullOrEmpty(base64Content))
        {
            throw new ArgumentNullException(nameof(base64Content));
        }

        int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);

        string dataLabel = base64Content.Substring(0, indexOfSemiColon);

        string contentType = dataLabel.Split(':').Last();

        var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;

        var fileContents = base64Content.Substring(startIndex);

        var bytes = Convert.FromBase64String(fileContents);

        return new Base64Image
        {
            ContentType = contentType,
            FileContents = bytes
        };
    }

    public string ContentType { get; set; }

    public byte[] FileContents { get; set; }

    public override string ToString()
    {
        return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
    }
}

var base64Img = new Base64Image { 
  FileContents = File.ReadAllBytes("Path to image"), 
  ContentType="image/png" 
};

string base64EncodedImg = base64Img.ToString();

您可以使用
Server.Map
path来给出相对路径,然后您可以使用
base64
转换创建映像,或者只需将
base64
字符串添加到
image src

byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));

string base64ImageRepresentation = Convert.ToBase64String(imageArray);

因为我们大多数人都喜欢OneLiner:

Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
如果需要将其作为Base64字节数组:

Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
诸如此类

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function

这样更简单,先传递图像,然后传递格式

private static string ImageToBase64(Image image)
{
    var imageStream = new MemoryStream();
    try
    {           
        image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
        imageStream.Position = 0;
        var imageBytes = imageStream.ToArray();
        var ImageBase64 = Convert.ToBase64String(imageBytes);
        return ImageBase64;
    }
    catch (Exception ex)
    {
        return "Error converting image to base64!";
    }
    finally
    {
      imageStream.Dispose;
    }
}

您可以轻松地传递图像的路径以检索base64字符串

public static string ImageToBase64(string _imagePath)
    {
        string _base64String = null;

        using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
        {
            using (MemoryStream _mStream = new MemoryStream())
            {
                _image.Save(_mStream, _image.RawFormat);
                byte[] _imageBytes = _mStream.ToArray();
                _base64String = Convert.ToBase64String(_imageBytes);

                return "data:image/jpg;base64," + _base64String;
            }
        }
    }

希望这会有所帮助。

以下代码对我很有用:

string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);

根据得票最多的答案,更新为C#8。以下内容可以开箱即用。在
Image
之前添加了显式
System.Drawing
,因为默认情况下可能会从其他名称空间使用该类

public static string ImagePathToBase64(string path)
{
    using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    using MemoryStream m = new MemoryStream();
    image.Save(m, image.RawFormat);
    byte[] imageBytes = m.ToArray();
    tring base64String = Convert.ToBase64String(imageBytes);
    return base64String;
}

如果要将它们嵌入CSS,请考虑配置一个buil系统,例如Gulp.js,它可以为您处理此任务。您希望对路径字符串进行编码,还是在该位置对图像进行编码,并提供一个数据URI?@Smith,如果您的意思是从base64转换回
System.Drawing.Image
您可以像这样使用st:
var img=Image.FromStream(新内存流(convert.fromsbase64string(base64String))为什么还要麻烦重新保存它呢?您可以读取文件的字节并进行转换。在我的情况下,这是因为我想在加载后调整图像的大小。@nyrguds我认为这是因为根据
图像判断它需要原始格式。RawFormat
@facepalm42
RawFormat
不是图像格式说明符;它是
图像
对象的一个属性,它返回从文件读取图像时的格式,这意味着在本例中,它将返回gif格式。因此,它不会改变任何内容,只是将图像的字节由.Net framework重新保存为gif,而不是实际原始文件的字节。请注意,由于某些原因,.Net不会将加载的动画gif视为调色板图像(仅发生在动画gif上,尽管也发生在动画gif上),并且在重新保存时会说“高颜色”对于调色板格式的图像,它使用标准的Windows 256调色板。由于动画gif通常有一个优化的调色板,这意味着通过此过程保存的任何动画gif都会严重降低其质量。所以这个设置肯定不理想,;正如KansaiRobot的回答所示,只读取原始字节要好得多。您注意到问题上的
C#
标记了吗?如果输入是gif,可能会出现问题;它将其重新保存为相同的类型(从
\u image.RawFormat
获取),但将数据公开为mime类型
image/jpg
您只需
返回Convert.ToBase64String(File.ReadAllBytes(path)),即可替换整个内容。甚至不需要涉及
System.Drawing