如何读取一个图像文件到字节[]

本文关键字:文件 图像 一个 到字节 何读取 读取 | 更新日期: 2023-09-27 18:07:20

这是我保存图片的方法。

[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);
        //...
    }
}

我不想显示那个位置的图像。我想先读一下,以便进一步处理。

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

如何读取一个图像文件到字节[]

Update:将图像读取为字节[]

// 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 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);