Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.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#_C# 4.0_Image Processing_Base64 - Fatal编程技术网

C# 如何在不损失图像质量的情况下将图像转换为base64格式?

C# 如何在不损失图像质量的情况下将图像转换为base64格式?,c#,c#-4.0,image-processing,base64,C#,C# 4.0,Image Processing,Base64,我已经实现了两个Winform应用程序,一个用于图像到base64的转换,另一个用于base64字符串到图像的转换。 上述应用程序的输出是base64字符串。 例如,代码是 public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format) { using (MemoryStream ms = new MemoryStream()) {

我已经实现了两个Winform应用程序,一个用于图像到base64的转换,另一个用于base64字符串到图像的转换。 上述应用程序的输出是base64字符串。 例如,代码是

  public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }
在我的另一个应用程序(base64到图像转换)中,我将base64字符串转换为图像,该应用程序的输出是图像。 例如,代码是

 public Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }
与以前的图像相比,此图像的质量较差。如何解决此问题

与以前的图像相比,此图像的质量较差。如何解决此问题

传入一个基本上不会丢失质量的
ImageFormat
。这与base64编码部分无关——这只是一种将二进制数据转换为文本并返回的方法。它是无损的

为了向自己证明这一点,只需将图像保存到
MemoryStream
,将其倒带,然后从流中加载-您将看到完全相同的质量损失。解决了这个问题,当您使用base64将其编码为文本时,改进仍然存在