c# - 如何将 UlImage 作为 Base64 字符串传递给 Asp.Net Web Api
<p><p>我有以下适用于 iOS 10 Swift 3 的代码</p>
<pre><code>if let pic = info as? UIImage {
let sss = UIImagePNGRepresentation(pic)! as NSData
let s1 = sss.base64EncodedString(options: .lineLength64Characters)
// api call .....
}
</code></pre>
<p>在 C# Web API 中我正在关注</p>
<pre><code>byte[] imageBytes = Convert.FromBase64String(defultdr["@imageString"]);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms,true);
image.Save(ImageDirPath + defultdr["@imageName"]);
</code></pre>
<p>其中 <code>defultdr["@imageString"]</code> 包含来自 iOS Wwift 3 的 Base64 字符串形式的图像数据</p>
<p>但我得到以下异常</p>
<blockquote>
<p>Parameter is not valid.</p>
<p>at System.Drawing.Image.FromStream(Stream stream, Boolean
useEmbeddedColorManagement, Boolean validateImageData) at
System.Drawing.Image.FromStream(Stream stream) at
TWebApiSearch.Controllers.UploadController.ImageToDir(TRequest json)
in
C:\Users\tahmid\Downloads\APIWeb\TWebApiSearch\Controllers\UploadController.cs:line
53</p>
</blockquote>
<p>在 Web API C# 中的这一行</p>
<pre><code>Image image = Image.FromStream(ms,true);
</code></pre>
<p>这个错误的原因是什么?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您正在加载内存流两次。初始化一次时</p>
<pre><code>MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
</code></pre>
<p>第二,当你写的时候。 </p>
<pre><code>ms.Write(imageBytes, 0, imageBytes.Length);
</code></pre>
<p>不需要第二个,因为您在使用字节数组初始化内存流缓冲区时已经加载了它。</p>
<p>试试这个</p>
<pre><code>var imageBytes = Convert.FromBase64String(defultdr["@imageString"]);
var ms = new MemoryStream(imageBytes);
var image = Image.FromStream(ms,true);
image.Save(ImageDirPath + defultdr["@imageName"]);
</code></pre></p>
<p style="font-size: 20px;">关于c# - 如何将 UlImage 作为 Base64 字符串传递给 Asp.Net Web Api,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/42926005/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/42926005/
</a>
</p>
页:
[1]