Richard77
Richard77

Reputation: 21609

How to read an image file to a byte[]?

This is how I save images.

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

        //...
    }
}

I don't want to display the image from that location. I want rather to read it first for further processing.

How do I read the image file in that case?

Upvotes: 7

Views: 56344

Answers (1)

havardhu
havardhu

Reputation: 3616

Update: Reading the image to a byte[]

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

For history's sake, here's my answer before the question was clarified.

Do you mean loading it as a BitMap instance?

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

Upvotes: 27

Related Questions