c# - 当字节数组的源是 jpg 时,从存储的字节数组创建位图并保存到磁盘会引发 GDI+ 异常
问题描述
我希望有人可以帮助解决我将已提供给我的图像保存为字节数组的问题。
版本:
- .Net 框架 4.6.2
- C# 7.2
故事是
- 用户上传图片
- 我们序列化成一个字节数组并存储它
- 稍后我们获取该字节数组并创建一个内存流,并使用该流创建一个位图对象。
- 使用该位图对象保存到磁盘
当原始文件为 PNG 格式时,这一切都有效。但是,当它是 Jpg 格式时它会失败。
下面是一些示例代码,您可以将其粘贴在基本控制台应用程序中,只要您引用 System.Drawing,它就会运行。
static void Main(string[] args)
{
Console.WriteLine("Enter image file location");
var filePath = Console.ReadLine();
while (!File.Exists(filePath))
{
Console.WriteLine("Cannot find file. Try Again");
filePath = Console.ReadLine();
}
byte[] bytes = File.ReadAllBytes(filePath);
Bitmap image;
using (var stream = new MemoryStream(bytes))
{
image = new Bitmap(stream);
}
WriteToFile(image);
image.Dispose();
Console.ReadKey();
}
private static void WriteToFile(Bitmap image)
{
Console.WriteLine("Enter write location filename");
var fileName = Console.ReadLine();
image.Save(fileName);
Console.WriteLine($"File saved to {fileName}");
}
如果原始图像是 PNG,则可以正常工作,如果是 JPG,则失败。这是为什么?我看到位图类的 Save 方法有一个需要ImageFormat
实例的重载。但是只有我拥有的是原始字节数组,所以我不知道我的图像格式是什么。
任何帮助将不胜感激,谢谢!
编辑:我尝试将图像格式指定为 JPG,无论是从原始文件创建字节数组还是将其保存回磁盘(参见下面的代码),但使用 jpgs 时它仍然会继续失败。但是,Pngs 仍然可以正常工作
static void Main(string[] args)
{
Console.WriteLine("Enter jpg file location");
var filePath = Console.ReadLine();
while (!File.Exists(filePath))
{
Console.WriteLine("Cannot find file. Try Again");
filePath = Console.ReadLine();
}
byte[] bytes = CreateSerializedImage(filePath);
Image image;
using (var steram = new MemoryStream(bytes))
{
image = Image.FromStream(steram);
}
WriteToFile(image);
image.Dispose();
Console.ReadKey();
}
private static byte[] CreateSerializedImage(string filePath)
{
var image = Image.FromFile(filePath);
using (var stream = new MemoryStream())
{
image.Save(stream,ImageFormat.Jpeg);
return stream.ToArray();
}
}
private static void WriteToFile(Image image)
{
Console.WriteLine("Enter write location filename");
var fileName = Console.ReadLine();
image.Save(fileName, ImageFormat.Jpeg);
Console.WriteLine($"File saved to {fileName}");
}
解决方案
推荐阅读
- php - 使用 Laravel 基于过滤器导出到 Excel
- node.js - 使用 cookie 时必须提供 jwt 错误
- node.js - axios.get() 没有在客户端获取数据
- pyinstaller - Edge 和 Chrome 将 pyinstaller 标记为病毒
- windows - 在 vsphere 虚拟机管理程序上安装 Docker 问题
- python - 函数正在更改两个列表,而不是基于 Python 中的“0”的一个列表
- html - CSS圆翘曲不平滑/圆形
- python - 升级到 python3.10 后 Flask-Sitemap 出现问题
- python - 如何使用 columns.names(keys) 从 DB 获取数据?
- reactjs - 使用传递给 apexchart 选项的道具值反应错误