How to convert the base64 data to video - asp.net-mvc-3

I am recording the user video and sending the data to the controller. The controller will receive the base64 data as a string. Then i am converting the base64 string to bytes like:
public ActionResult Content(string data)
{
byte[] ret = System.Text.Encoding.Unicode.GetBytes(data);
FileInfo fil = new FileInfo("D://test.mp4");
MemoryStream stream = new MemoryStream(ret);
var getdata = stream.GetBuffer();
using (Stream sw = fil.OpenWrite())
{
sw.Write(getdata, 0, getdata.Length);
sw.Close();
}
}
The video is downloading but the video is not playing the content. Can any body tell me what's the reason.

You need to recover the original byte array from the base64 string - use FromBase64String for that.
public ActionResult Content(string data)
{
byte[] ret = Convert.FromBase64String(data);
FileInfo fil = new FileInfo("D://test.mp4");
using (Stream sw = fil.OpenWrite())
{
sw.Write(ret , 0, ret .Length);
sw.Close();
}
}
What your code is doing is treating the base64 string as a unicode string, which it isn't.

Related

Apache httpcomponents 5 chunked response

I am accessing an internal site that returns gzipped content. When the content reaches a certain size, the site returns a chunked response. I am using the Apache httpcomponents 5 CloseableHttpAsyncClient and the SimpleHttpRequest and SimpleHttpResponse. The internal site is a vendor product that can't be modified.
String encoding = getEncoding(response.getHeaders());
byte[] bytes;
byte[] bodyBytes = response.getBodyBytes();
if (encoding.equals("gzip")) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bodyBytes);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
bytes = IOUtils.toByteArray(gzipInputStream);
} else {
bytes = bodyBytes;
}
String html = new String(bytes, StandardCharsets.UTF_8);
I check for the response type as follows
private String getEncoding(Header[] headers) {
for (Header header : headers) {
if (header.getName().toLowerCase().equals("transfer-encoding")) {
return header.getValue();
}
if (header.getName().toLowerCase().equals("content-encoding")) {
return header.getValue();
}
}
return "";
}
I know that there is a ChunkedInputStream class, but the inputs to the constructor are not obviously available from the response
ChunkedInputStream(SessionInputBuffer buffer, InputStream inputStream)
Wraps session input stream and reads chunk coded input.
ChunkedInputStream(SessionInputBuffer buffer, InputStream inputStream, Http1Config http1Config)
Default constructor.
Do I need to use a different response type? If so, which one? Or is there a different way that is better?
Thanks for your help.

How can I save an image in sqliteconnection xamarin forms [duplicate]

I have the following two methods that handles taking photos from a camera and picking photos from a library. They're both similar methods as at the end of each method, I get an ImageSource back from the Stream and I pass it onto another page which has an ImageSource binding ready to be set. These two method work perfectly. The next step now is to save the Image in SQLite so I can show the images in a ListView later on. My question for the XamGods (Xamarin Pros =), what is the best way to save image in SQLite in 2019? I have been in the forums for hours and I still don't have a tunnel vision on what I want to do. I can either
Convert Stream into an array of bytes to save in Sqlite.
Convert ImageSource into an array of bytes (messy/buggy).
Somehow retrieve the actual Image selected/taken and convert that into an array of bytes into SQLite
I'm sorry if my question is general, but Xamarin does not provide a clear-cut solution on how to save images in SQLite and you can only find bits and pieces of solutions throughout the forums listed below.
How to save and retrieve Image from Sqlite
Load Image from byte[] array.
Creating a byte array from a stream
Thank you in advance!
private async Task OnAddPhotoFromCameraSelected()
{
Console.WriteLine("OnAddPhotoFromCameraSelected");
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
var stream = photo.GetStream();
photo.Dispose();
if (stream != null)
{
ImageSource cameraPhotoImage = ImageSource.FromStream(() => stream);
var parms = new NavigationParameters();
parms.Add("image", cameraPhotoImage);
var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);
if (!result.Success)
{
throw result.Exception;
}
}
}
private async Task OnAddPhotoFromLibrarySelected()
{
Console.WriteLine("OnAddPhotoFromLibrarySelected");
Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
if (stream != null)
{
ImageSource selectedImage = ImageSource.FromStream(() => stream);
var parms = new NavigationParameters();
parms.Add("image", selectedImage);
parms.Add("stream", stream);
var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);
if (!result.Success)
{
throw result.Exception;
}
}
}
As Jason said that you can save image path into sqlite database, but if you still want to save byte[] into sqlite database, you need to convert stream into byte[] firstly:
private byte[] GetImageBytes(Stream stream)
{
byte[] ImageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
ImageBytes = memoryStream.ToArray();
}
return ImageBytes;
}
Then load byte[] from sqlite, converting into stream.
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
For simple sample, you can take a look:
Insert byte[] in sqlite:
private void insertdata()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
using (var con = new SQLiteConnection(path))
{
Image image = new Image();
image.Content = ConvertStreamtoByte();
var result = con.Insert(image);
sl.Children.Add(new Label() { Text = result > 0 ? "insert successful insert" : "fail insert" });
}
}
Loading image from sqlite:
private void getdata()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
using (var con = new SQLiteConnection(path))
{
var image= con.Query<Image>("SELECT content FROM Image ;").FirstOrDefault();
if(image!=null)
{
byte[] b = image.Content;
Stream ms = new MemoryStream(b);
image1.Source = ImageSource.FromStream(() => ms);
}
}
}
Model:
public class Image
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
}

How to save and read a byte[] into a IsolatedStorageFile

i know how to save a string into the IsolatedStorageFile but what about a byte[] ?
for a string i do:
string enc = "myString";
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile("fileName", FileMode.Create))
{
var writer = new StreamWriter(stream);
writer.Write(enc);
writer.Close();
}
}
EDIT: okay i know now how to write, but how to read out the byte[] again?
Use BinaryWriter instead of StreamWriter.
To write a byte array, instead of enclosing your stream in a StreamWriter, use directly stream.Write. Or use a BinaryWriter.
For instance:
stream.Write(byteArray, 0, byteArray.Length);

return list of images as bytes in mvc 3

I am trying to return a list of images as bytes to display on my view.
I know how to return a single image by putting this in my controller
public FileContentResult DisplayImages(string packageID)
{
byte[] byteArray = imageConverter.GetImageAsBytes(
"\\filepath-to-image.jpeg");
return new FileContentResult(byteArray, "image/jpeg"
}
How do I modify this to return a list of byte[] and then according call it in my View.
Thanks
I'll assume you'll call this action from javascript.
In this case you could use the Json actionresult type to do this.
public ActionResult DisplayImages(string packageID)
{
byte[] byteArray = imageConverter.GetImageAsBytes(#"\filepath-to-image.jpeg");
return Json(new { imageList = new List<Byte[]>() { byteArray } });
}
you'll get an object with a imageList property which will be an Array of Array of Byte.

Converting text using Base64 in Linux and Windows

I need to encrypt text/files in base 64 so I can send them in an email (I can't do attachments). I can use openSSL and GPG in Linux to encrypt and decrypt but don't know how to do the same in Windows XP. Does anyone know a program that can do this for me in windows?
EDITED AGAIN
In this link you can find how to encode/decode files.
I attach sample code:
private string FileToBase64(string srcFilename)
{
if (!string.IsNullOrEmpty(srcFilename))
{
FileStream fs = new FileStream(srcFilename,
FileMode.Open,
FileAccess.Read);
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes,
Base64FormattingOptions.InsertLineBreaks);
return encodedData;
}
}
private void Base64ToFile(string src, string dstFilename)
{
if (!string.IsNullOrEmpty(dstFilename))
{
byte[] filebytes = Convert.FromBase64String(src);
FileStream fs = new FileStream(dstFilename,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None);
fs.Write(filebytes, 0, filebytes.Length);
fs.Close();
}
}

Resources