我尝试使用C#将流转换为图像,但图像显示已损坏。
以下是我获取BaseString表示的方式
byte[] imageArray = System.IO.File.ReadAllBytes(@"C:\Users\jay.raj\Desktop\images\images\tiger.jpg");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
现在我将其传递给一个函数,该函数将其转换为Stream并尝试将其转换为图像文件。
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
MemoryStream stream = new MemoryStream(byteArray);
UtilityHelper.UploadImageFormDevice(stream, ref ss);
以下是UploadImageFormDevice
功能:
public static ResponseBase UploadImageFormDevice(Stream image, ref string imageName)
{
ResponseBase rep = new ResponseBase();
try
{
string filname = imageName;
string filePath = @"C:\Users\jay.raj\Desktop\Upload\";
if (filname == string.Empty)
filname = Guid.NewGuid().ToString() + ".jpg";
filePath = filePath + "\\" + filname;
FileStream fileStream = null;
using (fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = image.Read(buffer, 0, bufferLen)) > 0)
{
fileStream.Write(buffer, 0, count);
}
fileStream.Close();
image.Close();
}
imageName = filname;
}
catch (Exception ex)
{
rep.Code = 1000;
rep.Message = "Server Error";
}
return rep;
}
答案 0 :(得分:0)
正如@naivists写的那样尝试替换这一行:
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
到这一行:
byte[] byteArray = Convert.FromBase64String(mySettingInfo.FileToUpload);
答案 1 :(得分:0)
您好像要将文件从@"C:\Users\jay.raj\Desktop\images\images\tiger.jpg"
转移到@"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg"
。
在您的情况下,您将文件读取为字节数组,将其转换为基本64位编码字符串,然后再转换为字节数组。这是不必要的并且容易出错。在你的情况下,你错过了解码。
如果你暂时忽略它是一个图像,并将其视为一堆字节,事情可能会变得更容易。
string srcPath = @"C:\Users\jay.raj\Desktop\images\images\tiger.jpg";
string dstPath = @"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg";
byte[] imageArray = System.IO.File.ReadAllBytes(srcPath);
System.IO.File.WriteAllBytes(dstPath, imageArray);