c# - 试图将 byte[] 转换为 jpg 文件

标签 c# image

<分区>

我有一个网络 API 服务,它接受图像 (byte[]) 作为发布/创建方法的数据的一部分。我将图像数据保存在 sql server blob 列中。当我使用相应的 get 方法时,我看到的数据是

“ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e...”(缩短)

当我查看原始图像的字节时,它们看起来就像那样(从我的二进制编辑器中截取):

![手动方法[( http://sdrv.ms/1bjgsnX )

我需要一种方法将我的数据转换为正确的 jpg 文件。我已经尝试了几件事,但最终不得不手动完成。我没有在这里包括我使用 Image 的尝试,但它们也有很多,但都没有成功。必须有一种更标准的方法来做我需要做的事情。对于所有这些方法,我使用相同的文件编写代码:

string base64String = Convert.ToBase64String(photoFromDB, Base64FormattingOptions.None);
//various methods to convert that to a byte[] tempBytes
string DestFilePath = "testManual.jpg";
System.IO.FileStream fs = new System.IO.FileStream(DestFilePath,
System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(tempBytes, 0, tempBytes.Length);
fs.Close();

以下是我的尝试和结果:

![所有方法[( http://sdrv.ms/1bjgegH )

//Manual method that works but I don’t like.
byte[] tempBytes = new byte[base64String.Length/2];
string tempString;
byte tempByte;
int count = 0;

for (int i = 0; i < base64String.Length; i = i+2)
{
    tempString = base64String.Substring(i, 2);
    tempByte = Convert.ToByte(tempString, 16);
    tempBytes[count++] = tempByte;
}

//Unicode convert
//I can see my data here but it has extra nulls included.

tempBytes = System.Text.Encoding.Unicode.GetBytes(base64String);



//UTF32 convert
//again can see my data but even more nulls included

tempBytes = System.Text.Encoding.UTF32.GetBytes(base64String);


//UTF7, UTF8, and Default, ASCII, BigEndianUnicodegive me the same output
//I can see my data but it isn’t correct yet

tempBytes = System.Text.Encoding.UTF7.GetBytes(base64String);
tempBytes = System.Text.Encoding.UTF8.GetBytes(base64String);
tempBytes = System.Text.Encoding.Default.GetBytes(base64String);
tempBytes = System.Text.Encoding.ASCII.GetBytes(base64String);
tempBytes = System.Text.Encoding.BigEndianUnicodegive.GetBytes(base64String);

我缺少的秘诀是什么?

最佳答案

我不太清楚你为什么要在这里尝试对任何内容进行 base64 编码/解码...如果你已经有一个字节数组,为什么不使用 File.WriteAllBytes(...); 将它们放入 JPEG 文件中?

关于c# - 试图将 byte[] 转换为 jpg 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21680886/

相关文章:

c# - 输入显示和隐藏密码

c# - 如何在选定的索引更改属性上找到 gridview 的数据键值?

javascript - 间接远程图像

html - CSS 背景边距顶部效果

c# - 当应用程序位于远程计算机上时,异常未定义

c# - 未应用 ASP.NET href CSS

python - 如何使用turtle.bgpic()返回图像

image - 用opencv比较两张图片的相似度?

java - LibGDx 图像在第二次后不显示

c# - C/C++ 等同于 C# 参数