c# - 如何将图像文件读取到 byte[]?

标签 c# file-io

这就是我保存图像的方式。

[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
    if (file != null)
    {
        var extension = Path.GetExtension(file.FileName);
        var fileName = Guid.NewGuid().ToString() + extension;
        var path = Path.Combine(Server.MapPath("~/Content/Photos"), fileName);
        file.SaveAs(path);

        //...
    }
}

我不想显示该位置的图像。我宁愿先阅读它以进行进一步处理。

在那种情况下我该如何读取图像文件?

最佳答案

更新:将图像读入字节[]

// Load file meta data with FileInfo
FileInfo fileInfo = new FileInfo(path);

// The byte[] to save the data in
byte[] data = new byte[fileInfo.Length];

// Load a filestream and put its content into the byte[]
using (FileStream fs = fileInfo.OpenRead())
{
    fs.Read(data, 0, data.Length);
}

// Delete the temporary file
fileInfo.Delete();

// Post byte[] to database

为了历史的缘故,这是我在澄清问题之前的回答。

您的意思是将其加载为 BitMap实例?

 BitMap image = new BitMap(path);

 // Do some processing
 for(int x = 0; x < image.Width; x++)
 {
     for(int y = 0; y < image.Height; y++)
     {
         Color pixelColor = image.GetPixel(x, y);
         Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
         image.SetPixel(x, y, newColor);
     }
 }

// Save it again with a different name
image.Save(newPath);

关于c# - 如何将图像文件读取到 byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7296534/

相关文章:

c# - 使用 iTextSharp 在系统中使用字体

c# - 在运行时更改按钮名称和事件处理

c++ - _stat 返回不可能的 errno 代码 132

c# - .Net 6.0 项目中的自托管 Asp.net Web API

c# - 我可以在 Mac 上用 C# 编程吗?

c# - 键为 List 的字典如何运行?

python - 以编程方式编辑 Python 源代码

java - 从数据文件中读取数据点

file-io - 读取文件 : "Bad repeat count" 时出现 Fortran 运行时错误

python - 读取部分文件,以特定单词停止和开始