我想使用 NancyFX 在服务器上上传文件。我这样做:
var fileStream = File.Create(path_to_file);
file.Value.Seek(0, SeekOrigin.Begin);
file.Value.CopyTo(fileStream);
fileStream.Close();
我也试过:
byte[] buffer;
using (var memoryStream = new MemoryStream())
{
file.Value.Seek(0, SeekOrigin.Begin);
file.Value.CopyTo(memoryStream);
buffer = memoryStream.ToArray();
}
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length);
ms.Position = 0;
Image img = Image.FromStream(ms, true);
img.Save(path);
还有这个:
File.WriteAllBytes(coverPath, buffer);
在我的 Windows PC 上运行良好。在Linux服务器上,正在保存图片,但图片内容与原始图片不符。 所以,这里是图像: 原图,即上传中:http://i.stack.imgur.com/mTsE2.jpg 保存的图像:http://i.stack.imgur.com/ORKn1.jpg 如果图像大小 < 900kb,图像保存良好,但有时也会出现线条。 请帮忙。
最佳答案
据我所知,你有一个文件流,你想将它保存为图像
这里是一个和平的代码,在 Windows 8 .net 4.5 和 Ubuntu 12 TLS 中使用 mono JIT 编译器版本 2.10.8.1 运行良好
class Program
{
static void Main(string[] args)
{
string fileName = @"img/mTsE2.jpg";
string destimationImage = @"img/dest.jpg";
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string pathToFile = Path.Combine(appPath, fileName);
if (!File.Exists(pathToFile))
{
Console.WriteLine("Cant find file {0}", pathToFile);
Console.ReadLine();
return;
}
MemoryStream memoryStream = new MemoryStream();
using (FileStream fileStream = File.Open(pathToFile, FileMode.Open))
{
Console.WriteLine("Source length: {0}", fileStream.Length);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
memoryStream.Write(bytes, 0, (int)fileStream.Length);
}
Console.WriteLine("memoryStream length {0}", memoryStream.Length);
string destPath = Path.Combine(appPath, destimationImage);
CopyAsImage(destPath, memoryStream);
Console.WriteLine("Done! Check file {0}",destPath);
Console.ReadLine();
}
private static void CopyAsImage(string fileName, Stream stream)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Image image = Image.FromStream(stream, true, true);
image.Save(fileName);
}
}
如果它仍然不起作用,请注意尺寸。事实上 int 是一个 Int32,它应该可以用于最多 2+Gigs 的字节数组
关于linux - 单声道流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24369517/