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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With