Skip to main content
 首页 » 编程设计

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

2024年02月13日13birdshome

<分区>

我有一个网络 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); 

我缺少的秘诀是什么?