Convert HttpPostedFileBase to byte[] - arrays

In my MVC application, I am using following code to upload a file.
MODEL
public HttpPostedFileBase File { get; set; }
VIEW
#Html.TextBoxFor(m => m.File, new { type = "file" })
Everything working fine .. But I am trying to convert the result fiel to byte[] .How can i do this
CONTROLLER
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = model.File; //Its not working .How can convert this to byte array
}
}

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.
For efficient purposes you could check whether the stream returned is already a MemoryStream:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}

You can read it from the input stream:
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs method. You might find the following blog post useful.

byte[] file = new byte[excelFile.ContentLength];
excelFile.InputStream.Read(file, 0, file.Length);
//Create memory stream object from your bytes
MemoryStream ms = new MemoryStream(file);
// Set WorkbookPart , Sheet
using (var myDoc = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(ms, true))

Related

With HelixToolkit.SharpDX.Wpf how do I set the DiffuseMap on a PhongMaterial from an ImageSource?

The DiffuseMap property of a PhongMaterial accepts a Stream.
If I have an ImageSource, how do I convert it to something acceptable to the property? Note that I need to be able to do this fast, in memory.
In the examples in the source code I can only find examples of loading images from file:
var image = LoadFileToMemory(new System.Uri(#"test.png", System.UriKind.RelativeOrAbsolute).ToString());
this.ModelMaterial = new PhongMaterial
{
AmbientColor = Colors.Gray.ToColor4(),
DiffuseColor = Colors.White.ToColor4(),
SpecularColor = Colors.White.ToColor4(),
SpecularShininess = 100f,
DiffuseAlphaMap = image,
DiffuseMap = LoadFileToMemory(new System.Uri(#"TextureCheckerboard2.dds", System.UriKind.RelativeOrAbsolute).ToString()),
NormalMap = LoadFileToMemory(new System.Uri(#"TextureCheckerboard2_dot3.dds", System.UriKind.RelativeOrAbsolute).ToString()),
};
LoadFileToMemory simply takes the bytes from a file and returns it as a MemoryStream.
By ImageSource you mean a BitmapSource or DrawingImage? ImageSource is the abstract base class for both of them.
If you have a BitmapSource you can convert it to a MemoryStream using:
private Stream BitmapSourceToStream(BitmapSource writeBmp)
{
Stream stream = new MemoryStream();
//BitmapEncoder enc = new PngBitmapEncoder();
//BitmapEncoder enc = new JpegBitmapEncoder();
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(writeBmp));
enc.Save(stream);
return stream;
}

ASP.Net MVC - Read File from HttpPostedFileBase without save

I am uploading the file by using file upload option. And i am directly send this file from View to Controller in POST method like,
[HttpPost]
public ActionResult Page2(FormCollection objCollection)
{
HttpPostedFileBase file = Request.Files[0];
}
Assume, i am uploading a notepad file. How do i read this file & append this text to string builder,, without save that file....
I'm aware about after SaveAs this file, we can read this file. But How do i read this file from HttpPostedFileBase without save?
This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here
You should convert the stream into byte array and then you can read file content
Please refer following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]
Hope this helps
UPDATE :
The stream that you get from your HTTP call is read-only sequential
(non-seekable) and the FileStream is read/write seekable. You will
need first to read the entire stream from the HTTP call into a byte
array, then create the FileStream from that array.
Taken from here
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = System.Text.Encoding.UTF8.GetString(binData);
An alternative is to use StreamReader.
public void FunctionName(HttpPostedFileBase file)
{
string result = new StreamReader(file.InputStream).ReadToEnd();
}
A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

Need serialize bitmap image silverlight

I need serialize custom class with bitmapImage(tagged by xmlIgnore right now).
I'm using xmlSerialization, but I think thats bad.Do you have some ideas how can I serialize my class??Probably you can provide some simple example??
class X
{
private BitmapImage someImage;
public BitmaImage{get;set}
}
Actually later I will be use WCF Service.
Thanks)
You can expose the image as a byte array, e.g.:
public byte[] ImageAsBytes
{
get { return BytesFromImage(someImage); }
set { someImage = ImageFromBytes(value); }
}
You can of course convert back using a stream and the StreamSource property.
You could convert the image to a Base64 string. Examples from here:
//Convert image to the string
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
//when deserializing, convert the string back to an image
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}

How to get Memory Stream/Base64 String from Image.Source?

I have a dynamically created Image control that is populated via a OpenFileDialog like:
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
using (FileStream stream = dialog.File.OpenRead())
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
myImage.Source = bmp;
}
}
I want to send the image back to the server in a separate function call, as string via a web service.
How do I get a memory stream / base64 string from myImage.Source
Here's an alternative which should work (without BmpBitmapEncoder). It's uses the FileStream stream to create the byte array that is then converted to a Base64 string. This assumes you want to do this within the scope of the current code.
Byte[] bytes = new Byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes);
Make sure you have http://imagetools.codeplex.com/
Then you can do this:
ImageSource myStartImage;
var image = ((WriteableBitmap) myStartImage).ToImage();
var encoder = new PngEncoder( false );
MemoryStream stream = new MemoryStream();
encoder.Encode( image, stream );
var myStartImageByteStream = stream.GetBuffer();
Then for Base64:
string encodedData = Convert.ToBase64String(myStartImageByteStream);

Using httpwebrequest to get image from website to byte[]

I want to read the raw binary of a PNG file on a website and store it into a byte[], so far I have something like this:
Uri imageUri = new Uri("http://www.example.com/image.png");
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imageUri);
using (HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.GetResponse())
{
using (BinaryReader lxBR = new BinaryReader(imgResponse.GetResponseStream()))
{
using (MemoryStream lxMS = new MemoryStream())
{
lnBuffer = lxBR.ReadBytes(1024);
while (lnBuffer.Length > 0)
{
lxMS.Write(lnBuffer, 0, lnBuffer.Length);
lnBuffer = lxBR.ReadBytes(1024);
}
lnFile = new byte[(int)lxMS.Length];
lxMS.Position = 0;
lxMS.Read(lnFile, 0, lnFile.Length);
}
}
}
but I can't use GetResponse on Silverlight because it is not Asynchronous (I think that's the reason) so instead I should be using BeginGetResponse, but I'm not completely clear on how to go about it. This is what I have so far:
HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.BeginGetResponse(new AsyncCallback(WebComplete), imgRequest);
using (imgResponse)
{
using (BinaryReader lxBR = new BinaryReader(imgResponse.GetResponseStream()))
{
/*Same*/
}
}
and
void WebComplete(IAsyncResult a)
{
HttpWebRequest req = (HttpWebRequest)a.AsyncState;
HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(a);
//...? Do I need something else here?
}
can someone explain me a little bit how to use the BeginGetResponse property and how do I use the AsyncCallback.
Thanks!
Note:
I'm new to silverlight and I've been following tutorials and borrowing from other responses here on StackOverflow:
(stackoverflow responce) what I need to do but not in silverlight
tutorial
WebRequest_in_Silverlight
is this valid Silverlight code?
HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.BeginGetResponse(new AsyncCallback(WebComplete), imgRequest);
Got it working, want to post it here in case anyone needs it.
I need to get this image and then modify it (byte level) Silverlight didn't let me save the image directly to a WriteableBitmap and thus I had to get the image with a WebClient as a stream and then save it to a byte[]
this is how I get the image (I already have the specific Uri):
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(uri)
so when the image is loaded the wc_OpenReadCompleted method is called and it does something like this:
int lengthInBytes = Convert.ToInt32(e.Result.Length);
BinaryReader br = new BinaryReader(e.Result);
byte[] buffer = new byte[lengthInBytes];
using (br)
{
for (int i = 0; i < lengthInBytes; i++)
{
buffer[i] = br.ReadByte();
}
}
at the end the buffer[] has all the bytes of the image (what I wanted)
I'm sure there are better ways of doing this but this is working for me ! )
note: at some point I need to convert the byte[] to a BitmapImage (that was easier than expected):
//imageInBytes is a byte[]
if (imageInBytes != null)
{
MemoryStream rawBytesStream = new MemoryStream(imageInBytes);
BitmapImage img = new BitmapImage();
img.SetSource(rawBytesStream);
return img;
}
I hope this helps anyone.
Use the OpenReadAsync method of the WebClient object. Attach to the OpenReadCompleted event of the WebClient. Use the Stream provided by the Result property of the event args.
Consider setting AllowReadStreamBuffering, this will fill the entire stream before raising the OpenReadCompleted. In either case its likely you can use this stream to complete you real task rather than coping it into a MemoryStream.

Resources