Reputation: 23
this will be a noob question. I'm new to c#
I have a file upload server control that I am using to save images to server.
I have, in my library, an image resize function with this parameter:
byte[] resizeImage(byte[] image, int witdh)
that i am supposed to use. now, i am saving my file to some path as upImage.saveas("filepath");
ok?
now, I want to resize this image and i cant figure how to convert that image to bytes???
where is the article to convert? everywhere i see, i can only see bytes to image but i want other way around..
please help?
Upvotes: 2
Views: 16291
Reputation: 2007
convert the file to bytes in fileuploadcontrol on post method
public ActionResult ServiceCenterPost(ServiceCenterPost model)
{
foreach (var file in model.FileUpload)
{
if (file != null && file.ContentLength > 0)
{
byte[] fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
string thumbpath = _fileStorageService.GetPath(fileName);
_fileStorageService.SaveFile(thumbpath, fileBytes);
}
}
}
Upvotes: 1
Reputation: 269368
Do you mean convert the saved file to a byte[]
array? If so, you can use File.ReadAllBytes
:
byte[] imageBytes = File.ReadAllBytes("example.jpg");
If you want to grab the byte[]
array directly from your FileUpload
control then you can use the FileBytes
property:
byte[] imageBytes = yourUploadControl.FileBytes;
Upvotes: 6
Reputation: 24403
You can use the Image.Save function, passing in a memory stream. Once it completes, you can use MemoryStream.Read or MemoryStream.ToArray to recover the bytes.
Upvotes: 0
Reputation: 71945
Well, the short answer is
File.ReadAllBytes("filepath");
But the long answer is, it doesn't sound like you have any idea what's going on, so I suggest you make sure that the image is actually encoded the way you think it is (Is it actually a bitmap on disk, or is it compressed? What does resizeImage
actually do with the bytes and what kind of image does it expect? Why doesn't resizeImage
take an Image
and just resize it with GDI+?) Otherwise you might be in for a surprise.
Upvotes: 0
Reputation: 49978
Looks like you can save it to a MemoryStream
then convert the MemoryStream
to a byte array. From here
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray
}
Upvotes: 6