Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

file-io

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?

like image 684
Richard77 Avatar asked Sep 03 '11 23:09

Richard77


People also ask

How do I convert JPG to bytes?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How is an image stored in a byte array?

Any image is merely a sequence of bytes structured in accordance with whatever underlying format used to represent it, eg color data, layers, dimensions, etc. The significance of any byte(s) you see during debugging is entirely dependent upon the native format of the image, eg PNG, TIFF, JPEG, BMP, etc.

How do I convert a bitmap to a byte?

In addition, you can simply convert byte array to Bitmap . var bmp = new Bitmap(new MemoryStream(imgByte)); You can also get Bitmap from file Path directly. Save this answer.

How is an image represented in bytes?

Images are made of a grid of pixels aka “picture elements”. A pixel contains 8 bits (1 byte) if it is in BW (black and white). For colored images it uses a certain color scheme called RGB (Red, Green, Blue) represented as 1 byte each or 24 bits (3 bytes) per pixel. This is also referred to as the bit depth of an image.


1 Answers

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);
like image 171
havardhu Avatar answered Sep 17 '22 10:09

havardhu