I am having trouble rotating a scanned document that already has a qrcode on it.
I am checking for the qr code but when the code is upside down - i am having trouble flipping the page and trying to read for a qr code again. and i get this error message:
exception of type 'com.google.zxing.readerexception' was thrown
using (var fullImg = new Bitmap(workGif))
{
var halfW = fullImg.Width/2;
var halfH = fullImg.Height / 2;
var bandImg = fullImg.Clone(new System.Drawing.Rectangle(0, 0, halfW, halfH), fullImg.PixelFormat);
if (Process(bandImg) == null)
{
page.Rotate = (page.Rotate + 180) % 360;
}
string QRinfo = Process(bandImg);
MessageBox.Show(QRinfo);
string[] qcode = QRinfo.Split('/');
string gid = qcode[qcode.Count() - 1];
Guid pgGuid = new Guid(gid);
MessageBox.Show(QRinfo);
var ar = dc.Assessments.FirstOrDefault(c => c.ID == pgGuid);
if (ar != null)
{
var p = inputDocument.Pages[pg];
string opdName = FILESTORELOCATION + pgGuid.ToString() + ".pdf";
PdfDocument opd = new PdfDocument(opdName);
opd.Pages.Add(p);
opd.Close();
ar.StoragePath = opdName;
ar.LastUploadedDT = DateTime.UtcNow;
ar.UploadedByUserID = uploadingUser;
dc.SubmitChanges();
}
}
this is my process for decoding qr:
public string Process(Bitmap bitmap)
{
var reader = new com.google.zxing.qrcode.QRCodeReader();
try
{
LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
var binarizer = new HybridBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
return reader.decode(binBitmap).Text;
}
catch (Exception e)
{
return e.Message;
}
}
Related
I want to call a object from other method in CustomMapRenderer class in iOS project using this example
1. This is the method in which I call the object (I commented on it as a second line CodeNum).
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
//annotationView = new CustomMKAnnotationView(annotation, customPin.AlertLevel.ToString());
//annotationView.Image = UIImage.FromFile("pin.png");
annotationView.CalloutOffset = new CGPoint(0, 0);
//annotationView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("monkey.png"));
//annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
}
annotationView.CanShowCallout = true;
return annotationView;
}
2. In the second method I position where the content is after clicking the marker on the map with this method (I commented on it as a //the second text to enter in info window):
void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
CustomMKAnnotationView customView = e.View as CustomMKAnnotationView;
customPinView = new UIView();
if (customView.Name.Equals("Xamarin"))
{
customPinView.Frame = new CGRect(0, 0, 200, 84);
//var image = new UIImageView(new CGRect(0, 0, 200, 84));
//image.Image = UIImage.FromFile("xamarin.png");
//customPinView.AddSubview(image);
customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
//the first text to enter in info window
var labelAlertLevel = new UILabel(new CGRect(60, 0, 200, 84));
labelAlertLevel.Text = "Код на трвога (1-4): " + customView.AlertLevel.ToString();
customPinView.AddSubview(labelAlertLevel);
//the second text to enter in info window
var labelCodeNum = new UILabel(new CGRect(60, 20, 200, 84));
labelCodeNum.Text = "Код на станция: " + customView.CodeNum.ToString();
customPinView.AddSubview(labelCodeNum);
e.View.AddSubview(customPinView);
}
}
3. In this method I want to take the selection CodeNum but I don't know how:
CustomPin GetCustomPin(MKPointAnnotation annotation)
{
var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
int mapCode = int.Parse(pin.CodeNum.ToString());
var result = DataBaseConnection(mapCode);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
return pin;
}
}
return null;
}
My DataBaseConnection method look like:
public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
{
string ConnectionString = "server=192.168.0.3;uid=UserName;port=4443;pwd=Password;database=DBName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
var listAlert = new List<AlertLevel>();
try
{
Conn.Open();
//replace(2) with mapCode
string query = "CALL Get_Alert_levels_Station(" + mapCode + ");";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var currentData = new AlertLevel()
{
dateForecast = myReader.GetDateTime(0),
levelForecast = myReader.GetInt32(1)
};
listAlert.Add(currentData);
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
return listAlert;
}
**With this way result is filled with data when app is starting.. but I want to fill result every time when pin is clicked ?
My OnDidSelectAnnotationView method look like this:
void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
CustomMKAnnotationView customView = e.View as CustomMKAnnotationView;
customPinView = new UIView();
var customPin = GetCustomPin(annotation as MKPointAnnotation);
var result = DataBaseConnection(customPin.CodeNum);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
if (customView.Name.Equals("Xamarin"))
{
customPinView.Frame = new CGRect(0, 0, 200, 84);
customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
e.View.AddSubview(customPinView);
}
}
But I receive error: Error CS0103: The name 'annotation' does not exist in the current context (CS0103)
On this line:
var customPin = GetCustomPin(annotation as MKPointAnnotation);
CustomPin GetCustomPin(MKPointAnnotation annotation)
{
var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
int mapCode = int.Parse(pin.CodeNum);
var result = DataBaseConnection(mapCode);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
return pin;
}
}
return null;
}
You can move your query code into GetViewForAnnotation method, Once you get the Custompin from GetCustomPin method, you can easily get the CodeNum of Custompin
like:
var customPin = GetCustomPin(annotation as MKPointAnnotation);
var result = DataBaseConnection(customPin.CodeNum);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
//.......
Example:
public class CustomMapRenderer:MapRenderer
{IMKAnnotation c_annotation;
protected override MKAnnotationView
GetViewForAnnotation(MKMapView mp,IMKAnnotation annotation)
{//...
//set value
c_annotation=annotation;
//.....
}
void onDidSelectAnnotationView(object sender,MKAnnotationViewEventArgs e)
{//....
var pin=GetCustomPin(c_annotation as MKPointAnnotation);
//...
}
}
I am trying to convert ActionScript3 code to C# that's like the main thing. However, with trying to convert one of the functions I got the error which is in the title when I was trying to convert a hexadecimal string to an int.
Basically, this code is supposed to take information for example user data and then do somethings and in the end return Base64 encoded text. The main error that I am aware of is at the part where "loc9 = Convert.ToInt32(loc8, 16);" is as that is where I am getting the error said in the title. I have tried researching similar issues others have had with something like this, but it just didn't seem the same and didn't really help me out.
(Btw I am sorry if this doesn't sound so clear, correct me or ask more questions if not understood)
Screenshot of error when called
My C# Code:
private static string hasher(string input)
{
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
public static string p(string param1)
{
var loc6 = "";
var loc7 = "";
var loc8 = "";
var loc9 = 0;
var loc2 = hasher(param1);
var loc4 = 0;
MemoryStream loc0 = new MemoryStream();
var loc3 = new byte[] { };
while(loc4 < loc2.Length * 2)
{
loc6 = loc2.Substring(loc4, loc4 + 1);
loc7 = loc2.Substring(loc4 + 1, loc4 + 2);
loc8 = "0x" + loc6 + loc7;
loc9 = Convert.ToInt32(loc8, 16);
new BinaryWriter(loc0).Write(loc9);
loc4 = loc4 + 2;
}
loc0.Position = 0;
loc3 = loc0.ToArray();
return Convert.ToBase64String(loc3, 0, 16);
}
public string calculateFromNewActorCreationData(string username, string password, byte[] small, byte[] full)
{
return calculateFromStrings(username, password, small, full);
}
public string calculateFromStrings(string param1, string param2, object param3, object param4)
{
var loc5 = param1 + param2 + fromByteArray(param3 as byte[]) + fromByteArray(param4 as byte[]) + p();
return p(loc5);
}
private string fromByteArray(byte[] param1)
{
var ms = new MemoryStream(param1);
List<byte> list2 = new List<byte>();
if (param1.Length <= 20)
return HexStringFromBytes(param1);
var loc3 = new byte[] { };
var loc4 = param1.Length / 20;
var loc5 = 0;
while (loc5 < 20)
{
ms.Position = loc4 * loc5;
list2.Add(new BinaryReader(ms).ReadByte());
loc5++;
}
loc3 = list2.ToArray();
return HexStringFromBytes(loc3);
}
private static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
private string p()
{
MemoryStream stream = new MemoryStream();
new BinaryWriter(stream).Write(120);
new BinaryWriter(stream).Write(-38);
new BinaryWriter(stream).Write(99);
new BinaryWriter(stream).Write(16);
new BinaryWriter(stream).Write(32);
new BinaryWriter(stream).Write(51);
new BinaryWriter(stream).Write(41);
new BinaryWriter(stream).Write(-110);
new BinaryWriter(stream).Write(12);
new BinaryWriter(stream).Write(50);
new BinaryWriter(stream).Write(81);
new BinaryWriter(stream).Write(73);
new BinaryWriter(stream).Write(49);
new BinaryWriter(stream).Write(-56);
new BinaryWriter(stream).Write(13);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(14);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(46);
new BinaryWriter(stream).Write(2);
new BinaryWriter(stream).Write(0);
new BinaryWriter(stream).Write(45);
new BinaryWriter(stream).Write(-30);
new BinaryWriter(stream).Write(4);
new BinaryWriter(stream).Write(-16);
stream.Position = 0;
return Encoding.UTF8.GetString(stream.ToArray());
}
ActionScript3 Code:
private static function p(param1:String) : String
{
var _loc6_:String = null;
var _loc7_:String = null;
var _loc8_:String = null;
var _loc9_:int = 0;
var _loc2_:String = MD5.hash(param1);
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = 0;
while(_loc4_ < _loc2_.length * 2)
{
_loc6_ = _loc2_.slice(_loc4_,_loc4_ + 1);
_loc7_ = _loc2_.slice(_loc4_ + 1,_loc4_ + 2);
_loc8_ = "0x" + _loc6_ + _loc7_;
_loc9_ = int(_loc8_);
_loc3_.writeByte(_loc9_);
_loc4_ = _loc4_ + 2;
}
_loc3_.position = 0;
var _loc5_:Base64Encoder = new Base64Encoder();
_loc5_.encodeBytes(_loc3_,0,16);
return _loc5_.toString();
}
public function calculateFromNewActorCreationData(param1:NewActorCreationData, param2:ByteArray, param3:ByteArray) : String
{
return this.calculateFromStrings(param1.ChosenActorName,param1.ChosenPassword,param2,param3);
}
public function calculateFromStrings(param1:String, param2:String, param3:Object, param4:Object) : String
{
var _loc5_:String = param1 + param2 + this.fromByteArray(param3) + this.fromByteArray(param4) + this.p();
return p(_loc5_);
}
private function fromByteArray(param1:Object) : String
{
if(param1 == null)
{
return "";
}
var _loc2_:int = 20;
if(param1.length <= _loc2_)
{
return Hex.fromArray(param1 as ByteArray);
}
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = param1.length / _loc2_;
var _loc5_:int = 0;
while(_loc5_ < _loc2_)
{
param1.position = _loc4_ * _loc5_;
_loc3_.writeByte(param1.readByte());
_loc5_++;
}
return Hex.fromArray(_loc3_);
}
private function p() : String
{
var _loc1_:ByteArray = new ByteArray();
_loc1_.writeByte(120);
_loc1_.writeByte(-38);
_loc1_.writeByte(99);
_loc1_.writeByte(16);
_loc1_.writeByte(12);
_loc1_.writeByte(51);
_loc1_.writeByte(41);
_loc1_.writeByte(-118);
_loc1_.writeByte(12);
_loc1_.writeByte(50);
_loc1_.writeByte(81);
_loc1_.writeByte(73);
_loc1_.writeByte(49);
_loc1_.writeByte(-56);
_loc1_.writeByte(13);
_loc1_.writeByte(48);
_loc1_.writeByte(54);
_loc1_.writeByte(54);
_loc1_.writeByte(14);
_loc1_.writeByte(48);
_loc1_.writeByte(46);
_loc1_.writeByte(2);
_loc1_.writeByte(0);
_loc1_.writeByte(45);
_loc1_.writeByte(-30);
_loc1_.writeByte(4);
_loc1_.writeByte(-16);
_loc1_.uncompress();
_loc1_.position = 0;
return _loc1_.readUTF();
}
What I am expecting in the end is to be able to call the function having the returned Base64 encoded data show in a MessageBox (using messagebox as a test) instead of any errors popping up.
P.S - Besides the main problem I am having with this code, I also feel like the other functions I had converted aren't perfect or just might not be the same. So, if my main problem can be solved, if someone can also double check the other functions of my code make sure they are accurate that would be amazing and thanks in advance.
Looking at this overall, it appears the AS3 code is attempting to convert the MD5.hash result into a Base64 encoded string in the worst way possible (I believe it can be done in one line.)
So, instead of copying all the code to translate the hash to a hex string only to poorly translate it back to a binary array, just use the C# result which is already a binary array directly:
public static string p(string param1) {
byte[] loc3 = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(param1));
return Convert.ToBase64String(loc3, 0, 16);
}
Trying to stitch multiple videos using AVAssetTrack and AVMutableCompositionTrack. Uploaded videos could have different audio settings (e.g. sample rate) - what's the best way to pass in desired audio settings when adding AVAssetTracks to AVMutableVideoComposition? Currently using the following code, certain videos with 48KHz stitched with 44.1KHz produce no sound when played on IE/Edge, but works on other browsers:
Composition = new AVMutableComposition();
AVMutableCompositionTrack VideoCompositionTrack = Composition.AddMutableTrack(AVMediaType.Video, 0);
AVMutableCompositionTrack AudioCompositionTrack = Composition.AddMutableTrack(AVMediaType.Audio, 1);
AVMutableVideoCompositionLayerInstruction LayerInstruction = AVMutableVideoCompositionLayerInstruction.FromAssetTrack(VideoCompositionTrack);
CMTime StartTime = CMTime.Zero;
AVUrlAssetOptions Options = new AVUrlAssetOptions
{
PreferPreciseDurationAndTiming = true
};
CMTimeRange TimeRange;
NSError InsertError = null;
int Counter = 0;
CGSize FinalRenderSize = new CGSize();
foreach (NSUrl VideoLocation in SelectedVideoLocations)
{
using (AVAsset Asset = new AVUrlAsset(VideoLocation, Options))
{
TimeRange = new CMTimeRange()
{
Start = CMTime.Zero,
Duration = Asset.Duration
};
if (Asset.TracksWithMediaType(AVMediaType.Video).Length > 0)
{
using (AVAssetTrack VideoAssetTrack = Asset.TracksWithMediaType(AVMediaType.Video)[0])
{
if (Counter == 0)
{
FinalRenderSize = VideoAssetTrack.NaturalSize;
}
LayerInstruction.SetTransform(VideoAssetTrack.PreferredTransform, StartTime);
VideoCompositionTrack.InsertTimeRange(TimeRange, VideoAssetTrack, StartTime, out InsertError);
}
}
if (Asset.TracksWithMediaType(AVMediaType.Audio).Length > 0)
{
using (AVAssetTrack AudioAssetTrack = Asset.TracksWithMediaType(AVMediaType.Audio)[0])
{
LayerInstruction.SetTransform(AudioAssetTrack.PreferredTransform, StartTime);
AudioCompositionTrack.InsertTimeRange(TimeRange, AudioAssetTrack, StartTime, out InsertError);
}
}
StartTime = CMTime.Add(StartTime, Asset.Duration);
Counter++;
}
}
AVMutableVideoCompositionInstruction MainInstruction = new AVMutableVideoCompositionInstruction
{
TimeRange = VideoCompositionTrack.TimeRange,
LayerInstructions = new AVVideoCompositionLayerInstruction[1] { LayerInstruction }
};
AVMutableVideoComposition CompositionInstruction = AVMutableVideoComposition.Create(Composition);
CompositionInstruction.Instructions = new AVMutableVideoCompositionInstruction[1] { MainInstruction };
CompositionInstruction.FrameDuration = new CMTime(1, 30);
CompositionInstruction.RenderScale = 1.0f;
CompositionInstruction.RenderSize = FinalRenderSize;
string FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), FolderName, FileName);
await LocalStorage.DeleteFileAsync(FilePath);
NSUrl FilePathURL = NSUrl.CreateFileUrl(new string[] { FilePath });
MediaURL = FilePath;
AVAssetExportSession ExportSession = new AVAssetExportSession(Composition, AVAssetExportSessionPreset.Preset960x540);
if (CompositionInstruction != null)
{
ExportSession.VideoComposition = CompositionInstruction;
}
ExportSession.ShouldOptimizeForNetworkUse = true;
ExportSession.OutputUrl = FilePathURL;
ExportSession.OutputFileType = AVFileType.Mpeg4;
await ExportSession.ExportTaskAsync();
if (ExportSession.Status != AVAssetExportSessionStatus.Completed)
{
throw new Exception(ExportSession.Error.DebugDescription);
}
Is there a simple way to get the public static string result to the controller.
So im trying to make so when you upload you're image it gets resized.
i made a following code in my Toolbox
public static string ImageUpload(HttpPostedFileBase file, string SubFolder)
{
Guid gi = Guid.NewGuid();
string extension = Path.GetExtension(file.FileName);
using (var image = Image.FromStream(file.InputStream, true, true))
{
var thumbWidth = 700;
var thumbHeight = 700;
if (image.Width < image.Height)
{
//portrait image
thumbHeight = 640;
var imgRatio = (float)thumbHeight / (float)image.Height;
thumbWidth = Convert.ToInt32(image.Width * imgRatio);
}
else
if (image.Height < image.Width)
{
//landscape image
thumbWidth = 960;
var imgRatio = (float)thumbWidth / (float)image.Width;
thumbHeight = Convert.ToInt32(image.Height * imgRatio);
}
using (var thumb = image.GetThumbnailImage(
thumbWidth,
thumbHeight,
() => false,
IntPtr.Zero))
{
var jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (var encParams = new EncoderParameters(1))
{
string thumbPath = "~/Content/admin/images/" + SubFolder;
bool isExists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(thumbPath));
if (!isExists)
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(thumbPath));
}
var thumbPathFull = Path.Combine(HttpContext.Current.Server.MapPath(thumbPath), gi + extension);
string newfileurl = "/Content/admin/images/" + SubFolder + gi + extension;
long quality = 1500;
encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
thumb.Save(thumbPathFull, jpgInfo, encParams);
return newfileurl;
}
}
}
so i want the value "return newfileurl;" to my controller so how do i call it. so i can save the the string to my db to get the image frontend
[HttpPost]
[ValidateInput(false)]
public ActionResult NewsCreate(NewsItem ni, HttpPostedFileBase file)
{
Guid gi = Guid.NewGuid();
if (file != null && file.ContentLength > 0)
{
CRUDHelper.ImageUpload(file, "newsimage");
ni.Image = **??????insert solution here??????**;
db.NewsItems.Add(ni);
db.SaveChanges();
}
CRUDHelper.ImageUpload(file, "newsimage"); already returns the result, you only have to assign it to something: ni.Image = CRUDHelper.ImageUpload(file, "newsimage");
– HimBromBeere
I'm building an android app with Xamarin which communicates with an ASP.net server's API. I'm trying to upload a file to the server using the following lines of code:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
//progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = "myvideooo.mp4", username = "psyoptica" };
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
The app crashes before the server receives the request. The file I'm trying to upload could be a video or an audio file. The server receives the request after the app has crashed. This works fine on the local server but the crash happens with the live server. My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
File.WriteAllBytes(tempFilePath, model.data);
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
else
{
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}`
What am I doing wrong here that's making the app crash. Is there a better way to do this?
Any help is appreciated.