protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_DRAWCLIPBOARD: if (Clipboard.ContainsImage()) { NewImage?.Invoke(null, EventArgs.Empty); } SendMessage(this.NextClipBoardViewerHandle, m.Msg, m.WParam, m.LParam); break; case WM_CHANGECBCHAIN: if (m.WParam == NextClipBoardViewerHandle) { NextClipBoardViewerHandle = m.LParam; } else { SendMessage(NextClipBoardViewerHandle, m.Msg, m.WParam, m.LParam); } break; default: base.WndProc(ref m); break; } base.WndProc(ref m); }
IEnumerator Win() { isWin = true; OldImage.color = new Color(1, 1, 1, 0); NewImage.color = new Color(1, 1, 1, 0); //WinText.DOFade(1, 1f); OldImage.DOFade(1, 0.3f); yield return(new WaitForSeconds(0.3f)); NewImage.DOFade(1, 1.75f); yield return(new WaitForSeconds(2.5f)); if (SceneManager.GetActiveScene().buildIndex + 1 < SceneManager.sceneCountInBuildSettings) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } else { OldImage.color = Color.clear; /* * NewImage.DOFade(0.8f, 0.25f); * yield return new WaitForSeconds(1f); * NewImage.DOFade(0.6f, 0.2f); * yield return new WaitForSeconds(0.8f); * NewImage.DOFade(0.3f, 0.2f); * yield return new WaitForSeconds(1.5f);*/ NewImage.DOFade(0f, 3f); WinText.DOFade(1, 3f); } }
private void HandleImagePacket(object[] Values) { try { Byte[] Message = (Byte[])Values[1]; Int32 Width = (Int32)Values[2]; Int32 Height = (Int32)Values[3]; //Int32 R = (Int32)Values[4]; //Int32 G = (Int32)Values[5]; //Int32 B = (Int32)Values[6]; System.Drawing.Image MessageImg = ByteToImage(Message, Width, Height); // //Int32 RealR = MessageImg.GetPixel(30, 30).R; //Int32 RealG = MessageImg.GetPixel(30, 30).R; //Int32 RealB = MessageImg.GetPixel(30, 30).R; NewImage?.Invoke(MessageImg); } catch (Exception ex) { NewMessage?.Invoke(ex.Message); } }
public async Task PutImage(string path) { string imageBase64 = ImageToBase64(new Bitmap(path)); SelectedImage = new ClassifiedImage() { Id = -1, Name = Path.GetFileName(path), Class = -1, Confidence = -1, RetrieveCount = -1, ImageBase64 = imageBase64 }; await Task.Run(() => { HttpClient httpClient = new HttpClient(); NewImage newImage = new NewImage() { Name = Path.GetFileName(path), ImageBase64 = imageBase64 }; string json = JsonConvert.SerializeObject(newImage); var content = new StringContent(json); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var putResult = httpClient.PutAsync(Urls.ClassifiedImages, content).Result; json = putResult.Content.ReadAsStringAsync().Result; Dispatcher.UIThread.InvokeAsync(() => { SelectedImage = JsonConvert.DeserializeObject <ClassifiedImage>(json); }); }); }
public void ResizeImage(string OrigFile, string NewFile, int NewWidth, int MaxHeight, bool ResizeIfWider) { FullSizeImage = Image.FromFile(OrigFile); // Ensure the generated thumbnail is not being used by rotating it 360 degrees FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (ResizeIfWider) { if (FullSizeImage.Width <= NewWidth) { NewWidth = FullSizeImage.Width; } } int NewHeight = FullSizeImage.Height * NewWidth / FullSizeImage.Width; if (NewHeight > MaxHeight) { // Height resize if necessary NewWidth = FullSizeImage.Width * MaxHeight / FullSizeImage.Height; NewHeight = MaxHeight; } // Create the new image with the sizes we've calculated NewImage = FullSizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); FullSizeImage.Dispose(); jpgEncoder = GetEncoder(ImageFormat.Jpeg); // Create an Encoder object based on the GUID for the Quality parameter category. System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; // Create an EncoderParameters object. An EncoderParameters object has an array of EncoderParameter objects. In this case, there is only one EncoderParameter object in the array. myEncoderParameters = new EncoderParameters(1); myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; NewImage.Save(NewFile, jpgEncoder, myEncoderParameters); }
public static Result[] SearchSegmFree(NewImage QueryImage, ConcurrentDictionary <string, DocumentInfo> Dataset) { var myDSLPLibrary = new DoLF(); var myDSLPpoints = myDSLPLibrary.GetDSLPoints(QueryImage.Data, QueryImage.Width, QueryImage.Height, 3); var queryVector = myDSLPLibrary.CreateNormalizedDescriptorForSegmFree(myDSLPpoints); var results = new ConcurrentBag <Result>(); //Parallel.ForEach(Dataset.Keys, doc => foreach (var doc in Dataset.Keys) { var _results = myDSLPLibrary.DistanceSegmFree(queryVector, QueryImage.Width, QueryImage.Height, Dataset[doc].Descriptors); foreach (var r in _results) { results.Add(new Result { X = (short)r.Block[0], Y = (short)r.Block[1], Width = (short)r.Block[2], Height = (short)r.Block[3], Similarity = r.Similarity, Document = doc }); } } return(results.OrderBy(x => x.Similarity).ToArray()); }
private void CopyScreen() { Bitmap b = new Bitmap(Tasks.MaxSearchArea.Width, Tasks.MaxSearchArea.Height); using (var g = Graphics.FromImage(b)) { g.CopyFromScreen(Tasks.HeightestSearchPosition.X, Tasks.HeightestSearchPosition.Y, 0, 0, Tasks.MaxSearchArea); } NewImage?.Invoke(b); }
public NewsImageViewModel ToNewImageViewModel(NewImage newimg) { return(new NewsImageViewModel { Id = newimg.Id, New_id = newimg.New.Id, New = newimg.New, ImageUrl = newimg.ImageUrl, }); }
public ClassifiedImage Classify(NewImage newImage) { MNISTModelResult result = model.PredImage(Convert.FromBase64String(newImage.ImageBase64)); return(new ClassifiedImage() { Name = newImage.Name, Class = result.Class, Confidence = result.Confidence, RetrieveCount = 0, ImageBase64 = newImage.ImageBase64 }); }
public ClassifiedImage PutImage(NewImage newImage) { ClassifiedImage classifiedImage = db.FindImage(newImage); if (classifiedImage != null) { return(classifiedImage); } classifiedImage = classifier.Classify(newImage); db.PutImage(classifiedImage); return(classifiedImage); }
public static float[] GetDescriptor(string ImageBase64) { using var memoryStream = new MemoryStream(Convert.FromBase64String(ImageBase64)) { Position = 0 }; Bitmap bmpImage = (Bitmap)Image.FromStream(memoryStream); var img = new NewImage(bmpImage); var myDSLPLibrary = new DoLF(); var myDSLPpoints = myDSLPLibrary.GetDSLPoints(img.Data, img.Width, img.Height, 3); return(myDSLPLibrary.CreateNormalizedDescriptorForSegmFree(myDSLPpoints)); }
public void MakeAnimationReverse() { if (images != null) { int to = ActualPage - 1; ActualPage--; if (to < 0) { to = images.Count - 1; ActualPage = images.Count - 1; } if (!reverse) { Canvas.SetLeft(CurrentImage, 0); Canvas.SetLeft(NewImage, CurrentImage.Width); NewImage.Source = imgS[to]; DoubleAnimation moveAnimX = new DoubleAnimation(Canvas.GetLeft(CurrentImage), CurrentImage.Width, new Duration(TimeSpan.FromSeconds(TimeToTranslate))); DoubleAnimation NmoveAnimX = new DoubleAnimation(-CurrentImage.Width, 0, new Duration(TimeSpan.FromSeconds(TimeToTranslate))); moveAnimX.DecelerationRatio = 0.5f; NmoveAnimX.DecelerationRatio = 0.5f; CurrentImage.BeginAnimation(Canvas.LeftProperty, moveAnimX); NewImage.BeginAnimation(Canvas.LeftProperty, NmoveAnimX); reverse = true; } else { Canvas.SetLeft(NewImage, 0); Canvas.SetLeft(CurrentImage, CurrentImage.Width); CurrentImage.Source = imgS[to]; DoubleAnimation moveAnimX = new DoubleAnimation(Canvas.GetLeft(NewImage), NewImage.Width, new Duration(TimeSpan.FromSeconds(TimeToTranslate))); DoubleAnimation NmoveAnimX = new DoubleAnimation(-CurrentImage.Width, 0, new Duration(TimeSpan.FromSeconds(TimeToTranslate))); moveAnimX.DecelerationRatio = 0.5f; NmoveAnimX.DecelerationRatio = 0.5f; NewImage.BeginAnimation(Canvas.LeftProperty, moveAnimX); CurrentImage.BeginAnimation(Canvas.LeftProperty, NmoveAnimX); reverse = false; } CanGoToNext = false; CanGoTimer = TimeToTranslate; UpdateCirclesAndText(); } }
public async Task <IActionResult> OnPostAsync(int id) { if (!ModelState.IsValid) { return(Page()); } player = await _context.Players .Include(p => p.Position).FirstOrDefaultAsync(m => m.ID == id); _context.Attach(player).State = EntityState.Modified; try { if (NewImage != null && NewImage.Length > 0) { using (var ms = new MemoryStream()) { NewImage.CopyTo(ms); var fileBytes = ms.ToArray(); var resizedImage = ImageUtils.ResizeImage(fileBytes, 140, 190); player.Image = resizedImage; } } player.FirstName = PlayerModel.FirstName; player.LastName = PlayerModel.LastName; player.DOB = PlayerModel.DOB; player.Email = PlayerModel.Email; player.PositionId = PlayerModel.PositionId; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PlayerExists(id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }
public static void OnNewImage(Bitmap b) { if (MyForm.pictureBox1.InvokeRequired) { NewImage dd = OnNewImage; MyForm.Invoke(dd, b); } else { if (MyForm.pictureBox1.Image != null) { MyForm.pictureBox1.Image.Dispose(); } MyForm.pictureBox1.Image = b.Clone() as Bitmap; MyForm.Text = string.Format("Time: {0}ms, Cross found: {1}", millis, CWrapper.GetCrossFound()); } }
public void AddImageExecute() { NewImage.Validate(); if (!NewImage.IsValid) { return; } else { NewImage.Date = DateTime.Now; _repo.AddImage(MainViewModel.logedInUser, NewImage); MainViewModel.logedInUser.MyImages.Add(NewImage); AppViewModel.Instance.Images(); AppViewModel.Instance.OnNav("images"); Info = "Picture added to My Pictures!"; } }
private void backgroundWorkerImages_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; IList <FileInfo> FileCollection = e.Argument as IList <FileInfo>; foreach (FileInfo File in FileCollection) { if ((worker.CancellationPending == true)) { e.Cancel = true; break; } else { try { Image image = Image.FromFile(File.FullName); if (image.Height > numericUpDownHeight.Value || image.Width > numericUpDownWidth.Value) { //Keep the ratio aspect decimal ratio = (decimal)image.Height / (decimal)image.Width; Image NewImage; NewImage = GetResizedImage(image, (int)numericUpDownWidth.Value, (int)numericUpDownHeight.Value); NewImage.Save(Path.Combine(PathDestinationtextBox.Text, Properties.Settings.Default.ResizedPrefix + File.Name)); //ImageFormat.Jpeg); } image.Dispose(); worker.ReportProgress(1); } catch (Exception ex) { /*MessageBox.Show("Se produjo la siguiente excepción: ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); * backgroundWorkerImages.CancelAsync();*/ } } } }
public string Temp(HttpPostedFileBase file) { try { var session = (UserLogin)Session[Web_ban_hang.Common.CommonConstants.USER_SESSION]; if (file != null) { if (!Directory.Exists(Server.MapPath("~/Upload/Temp/") + session.UserName)) { Directory.CreateDirectory(Server.MapPath("~/Upload/Temp/") + session.UserName); } int fileSize = file.ContentLength; var random = new Random(); string fileName = random.Next(0, int.MaxValue) + file.FileName; var date = DateTime.Now.ToString("dd-MM-yyyy"); file.SaveAs(Path.Combine(Server.MapPath("~/Upload/Temp/" + session.UserName + "/"), date + "-" + fileName)); NewImage images = new NewImage(); images.image = "/Upload/Temp/" + session.UserName + "/" + date + "-" + fileName; images.link = session.UserID + "-" + date + "-" + fileName; images.ten = session.UserID; var hinh = Session[CommonConstants.IMAGE_SESSION]; if (hinh != null) { var list = (List <NewImage>)hinh; list.Add(images); Session[CommonConstants.IMAGE_SESSION] = list; } else { List <NewImage> image = new List <NewImage>(); image.Add(images); Session.Add(CommonConstants.IMAGE_SESSION, image); } return("/Upload/Temp/" + session.UserName + "/" + date + "-" + fileName); } else { return("loi"); } } catch (Exception) { return("loi"); } }
public static ConcurrentDictionary <string, DocumentInfo> IndexingSegmBased(string[] Documents, ProgressBar myProgressBar) { var Dataset = new ConcurrentDictionary <string, DocumentInfo>(); Parallel.ForEach(Documents, doc => { var img = new NewImage(doc); var myDSLPLibrary = new DoLF(); var myDSLPpoints = myDSLPLibrary.GetDSLPoints(img.Data, img.Width, img.Height, 3); var myDocInfo = new DocumentInfo { Descriptors = myDSLPLibrary.CreateNormalizedDescriptorForSegmBased(myDSLPpoints, img.Width, img.Height), Width = img.Width, Height = img.Height }; Dataset.TryAdd(Path.GetFileNameWithoutExtension(doc), myDocInfo); myProgressBar.Increase(100d / Documents.Length); }); return(Dataset); }
public NewBaseControl CreateControl(String controlType, Point position) { NewBaseControl control = null; switch (controlType) { case "Text": control = new NewText(); break; case "ActiveText": control = new NewActiveText(); break; case "Image": control = new NewImage(); break; case "ActiveImage": control = new NewActiveImage(); break; case "BackGroundImage": control = new NewBackGroundImage(); break; case "Line": control = new NewLine(); break; case "Table": control = new NewTable(); break; } control.ControlNum = Config.ElementNodeStartNum; control.ControlType = controlType; control.ControlPosition = position; control.Create(); return(control); }
private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count < 1) { return; } int index = dataGridView1.SelectedRows[0].Index; string RightKey = (string)dataGridView1[5, index].Value; Image newImage = new NewImage((Image)dataGridView1[4, index].Value, rightKey: RightKey).DeShifrovkaImage(Key); try { pictureBox1.Image = newImage; } catch (Exception) { pictureBox1.Image = pictureBox1.ErrorImage; } }
public ClassifiedImage FindImage(NewImage newImage) { using (ImageDbContext dbContext = new ImageDbContext()) { var dbImages = dbContext.ClassifiedImages. Where(img => img.Name.Equals(newImage.Name)). ToList(); if (dbImages.Any()) { ClassifiedDbImage dbImage = dbImages.First(); dbContext.Entry(dbImage).Reference(img => img.Image).Load(); if (Enumerable.SequenceEqual(dbImage.Image.Bytes, Convert.FromBase64String(newImage.ImageBase64))) { dbImage.RetrieveCount += 1; dbContext.SaveChanges(); return(FromDbImage(dbImage)); } } } return(null); }
public static Result[] SearchSegmBased(NewImage QueryImage, ConcurrentDictionary <string, DocumentInfo> Dataset) { var myDSLPLibrary = new DoLF(); var myDSLPpoints = myDSLPLibrary.GetDSLPoints(QueryImage.Data, QueryImage.Width, QueryImage.Height, 3); var queryVector = myDSLPLibrary.CreateNormalizedDescriptorForSegmBased(myDSLPpoints, QueryImage.Width, QueryImage.Height); var results = new ConcurrentBag <Result>(); Parallel.ForEach(Dataset.Keys, doc => { var r = myDSLPLibrary.DistanceSegmBased(queryVector, Dataset[doc].Descriptors); results.Add(new Result { X = 0, Y = 0, Width = Dataset[doc].Width, Height = Dataset[doc].Height, Similarity = r, Document = doc }); }); return(results.OrderBy(x => x.Similarity).ToArray()); }
public async Task <IActionResult> AddNewImage(NewsImageViewModel model) { if (ModelState.IsValid) { var path = string.Empty; if (model.ImageFile != null) { path = await _imageHelper.UpLoadImageAsync(model.ImageFile); } var newimg = new NewImage { ImageUrl = path, New = await _datacontext.News.FindAsync(model.Id) }; _datacontext.NewImages.Add(newimg); await _datacontext.SaveChangesAsync(); return(RedirectToAction($"NewImagetList/{model.New_id}")); } return(View(model)); }
//--------------------------------------------------------------------------------- public void AddImage(Image _image) { if (_image == null) { return; } NewImage dlg = new NewImage(Edited, _image); // try creating default image (faster create image without UI ... ) if ((ModifierKeys & Keys.Shift) == 0 && dlg.CreateWithoutUI()) { taxonListImage1.UpdateUI(); } else if (dlg.ShowDialog() == DialogResult.OK) { taxonListImage1.UpdateUI(); TaxonImageDesc imageDesc = dlg.GetImageDesc(); if (imageDesc != null) { taxonListImage1.SetImage(imageDesc); } } }
public static System.Drawing.Bitmap CropImage(System.Drawing.Image Image, int Width, int Height) { if ((Image != null)) { if (Image.Width > Width || Image.Height > Height) { decimal Ratio = Convert.ToDecimal(Image.Width) / Convert.ToDecimal(Image.Height); int SizedWidth = Image.Width; int SizedHeight = Image.Height; if (Ratio > 1) { if (Height > Image.Height) { Height = Image.Height; } SizedHeight = Height; SizedWidth = Convert.ToInt32(SizedHeight * Ratio); } else { if (Width > Image.Width) { Width = Image.Width; } SizedWidth = Width; SizedHeight = Convert.ToInt32(SizedWidth / Ratio); } System.Drawing.Bitmap NewImage = null; if (Image.PixelFormat.ToString().Contains("Indexed")) { NewImage = new System.Drawing.Bitmap(Convert.ToInt32(SizedWidth), Convert.ToInt32(SizedHeight)); } else { NewImage = new System.Drawing.Bitmap(SizedWidth, SizedHeight, Image.PixelFormat); } System.Drawing.Graphics Graph = System.Drawing.Graphics.FromImage(NewImage); Graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Graph.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; Graph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Rectangle Rect = new System.Drawing.Rectangle(0, 0, SizedWidth, SizedHeight); Graph.DrawImage(Image, Rect); System.Drawing.Rectangle CroppedRect = new System.Drawing.Rectangle((NewImage.Width - Width) / 2, (NewImage.Height - Height) / 2, Width, Height); System.Drawing.Bitmap BMP = NewImage.Clone(CroppedRect, NewImage.PixelFormat); return(BMP); } else { System.Drawing.Bitmap NewImage = null; if (Image.PixelFormat.ToString().Contains("Indexed")) { NewImage = new System.Drawing.Bitmap(Convert.ToInt32(Image.Width), Convert.ToInt32(Image.Height)); } else { NewImage = new System.Drawing.Bitmap(Image.Width, Image.Height, Image.PixelFormat); } System.Drawing.Graphics Graph = System.Drawing.Graphics.FromImage(NewImage); Graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Graph.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; Graph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Rectangle Rect = new System.Drawing.Rectangle(0, 0, Image.Width, Image.Height); Graph.DrawImage(Image, Rect); return(NewImage); } } return(null); }
private unsafe void ProcessMultisourceFrame(MultiSourceFrame multiSourceFrame) { // Aquiure all frames using var depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); using var colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); using var bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); // If any frame has expired by the time we process this event, return. if (depthFrame == null || colorFrame == null || bodyIndexFrame == null) { return; } // Copy depth frame using var depthFrameData = depthFrame.LockImageBuffer(); _coordinateMapper.MapColorFrameToDepthSpaceUsingIntPtr(depthFrameData.UnderlyingBuffer, depthFrameData.Size, _colorMappedToDepthPoints); var depthFrameDescription = depthFrame.FrameDescription; var depthWidth = depthFrameDescription.Width; var depthHeight = depthFrameDescription.Height; // Copy color frame ColorImageLock.EnterWriteLock(); fixed(byte *ColorImagePtr = ColorImage) { using var colorFrameData = colorFrame.LockRawImageBuffer(); var colorFrameSpan = new Span <byte>((void *)colorFrameData.UnderlyingBuffer, (int)colorFrameData.Size); var colorImageSpan = new Span <byte>((void *)ColorImagePtr, ColorImageLength); var colorImageSpanUInt32 = new Span <UInt32>((void *)ColorImagePtr, ColorImageLength); //colorFrameSpan.CopyTo(colorImageSpan); colorFrame.CopyConvertedFrameDataToArray(ColorImage, ColorImageFormat.Bgra); // Get body index data using var bodyIndexData = bodyIndexFrame.LockImageBuffer(); var bodyIndexDataPointer = (byte *)bodyIndexData.UnderlyingBuffer; var colorMappedToDepthPointsPointer = new Span <DepthSpacePoint>(_colorMappedToDepthPoints); // Go over and black out all colors that are not a body index for (var colorIndex = 0; colorIndex < colorMappedToDepthPointsPointer.Length; ++colorIndex) { float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. if (!float.IsNegativeInfinity(colorMappedToDepthX) && !float.IsNegativeInfinity(colorMappedToDepthY)) { // Make sure the depth pixel maps to a valid point in color space int depthX = (int)(colorMappedToDepthX + 0.5f); int depthY = (int)(colorMappedToDepthY + 0.5f); // If the point is not valid, there is no body index there. if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) { int depthIndex = (depthY * depthWidth) + depthX; // If we are tracking a body for the current pixel, do not zero out the pixel if (bodyIndexDataPointer[depthIndex] != 0xff) { // Set alpha to fully opaque // For some reason we are ARGB colorImageSpanUInt32[colorIndex] |= 0xFF000000; continue; } } } // Background colorImageSpanUInt32[colorIndex] = 0x00000000; } } ColorImageLock.ExitWriteLock(); NewImage?.Invoke(this, ColorImage); }
public PNewDocument(NewImage view) { }
public string UploadImage(HttpContext context, string UploadPathTemp, string UploadPath) { string savedFileName = ""; bool IsEncodeFileName = false; int Width = -1; int Height = -1; bool isCreateThumb = false; string json = ""; foreach (string file in context.Request.Files) { HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile; if (hpf.ContentLength == 0) { continue; } else { IsEncodeFileName = !String.IsNullOrEmpty(context.Request.QueryString["IsEncodeFileName"]) ? Convert.ToBoolean(context.Request.QueryString["IsEncodeFileName"]) : false; savedFileName = GetFileName(IsEncodeFileName, hpf.FileName); isCreateThumb = !String.IsNullOrEmpty(context.Request.QueryString["isCreateThumb"]) ? Convert.ToBoolean(context.Request.QueryString["isCreateThumb"]) : false; //Upload len thu muc temp hpf.SaveAs(UploadPathTemp + savedFileName); //Upload file //Resize neu can Height = !String.IsNullOrEmpty(context.Request.QueryString["Height"]) ? Convert.ToInt32(context.Request.QueryString["Height"]) : -1; Width = !String.IsNullOrEmpty(context.Request.QueryString["Width"]) ? Convert.ToInt32(context.Request.QueryString["Width"]) : -1; Image NewImage; if ((Height != -1) && (Width != -1)) { NewImage = ResizeImageFromFile(UploadPathTemp + savedFileName, Height, Width, false, false); //save sang thu muc thuc su NewImage.Save(UploadPath + savedFileName); } else if ((Height != -1) || (Width != -1)) { NewImage = ResizeImageFromFile(UploadPathTemp + savedFileName, Height, Width, true, true); //save sang thu muc thuc su NewImage.Save(UploadPath + savedFileName); } else { NewImage = Image.FromFile(UploadPathTemp + savedFileName); //save sang thu muc thuc su NewImage.Save(UploadPath + savedFileName); } //======================================= // Tao thumb if (isCreateThumb == true) { NewImage = ResizeImageFromFile(UploadPathTemp + savedFileName, 200, 200, false, true); NewImage.Save(UploadPath + "thumb_" + savedFileName); } NewImage.Dispose(); json = json + "{\"Status\":\"Success\",\"File\":\"" + (UploadPath + savedFileName).Replace("\\", "\\\\") + "\",\"Messenger\":\"" + "messsssss" + "\"}"; } } return(json); }
static void Main(string[] args) { var parsed = Parser.Default.ParseArguments <IndexingOptions, RetrievalOptions, DescriptorOptions, SearchOptions>(args).MapResult((IndexingOptions opts) => { string[] Documents = Directory.GetFiles(Path.GetFullPath(opts.ImagesDirectory), "*." + opts.ImageFormat); if (Documents.Length == 0) { Error("We do not found any images. Please check if you defined the image format correctly"); } var myProgressBar = new ProgressBar(); Console.WriteLine($"Found and Indexing {Documents.Length} Documents..."); var Dataset = new ConcurrentDictionary <string, Retrieval.DocumentInfo>(); var myWatch = new Stopwatch(); myWatch.Start(); Dataset = opts.Segm == Options.SegmentationType.SegmBased ? Retrieval.IndexingSegmBased(Documents, myProgressBar) : Retrieval.IndexingSegmFree(Documents, myProgressBar); myWatch.Stop(); double duration = myWatch.Elapsed.TotalSeconds / Documents.Length; Console.WriteLine("Done!"); Console.WriteLine($"Average Time per Document: {duration.ToString("0.00")} sec"); Console.WriteLine("Writing Database file..."); using (var file = File.CreateText(Path.GetFullPath(opts.OutputDatabaseFile))) { var serializer = new JsonSerializer(); serializer.Serialize(file, Dataset); } return(true); }, (RetrievalOptions opts) => { if (!File.Exists(opts.DatabaseFile)) { Error("The Database File does not exists!"); } string[] queries = Directory.Exists(opts.Query) ? Directory.GetFiles(opts.Query, $"*.{opts.ImageFormat.ToString()}") : new[] { opts.Query }; double duration = 0; var hKws14XMLFormat = new VCGXMLFormat.RelevanceListings { gtrels = new List <VCGXMLFormat.RelevanceListings.rel>() }; var concurrentGtRels = new ConcurrentBag <VCGXMLFormat.RelevanceListings.rel>(); Console.WriteLine("Loading Database to memory..."); ConcurrentDictionary <string, Retrieval.DocumentInfo> Dataset = null; using (var file = File.OpenText(opts.DatabaseFile)) { var serializer = new JsonSerializer(); Dataset = (ConcurrentDictionary <string, Retrieval.DocumentInfo>)serializer.Deserialize(file, typeof(ConcurrentDictionary <string, Retrieval.DocumentInfo>)); } Console.WriteLine($"Found {queries.Length} queries. Running..."); Stopwatch totalDuration = new Stopwatch(); totalDuration.Start(); var myProgressBar = new ProgressBar(); //foreach (var q in queries) Parallel.ForEach(queries, q => { var queryimg = new NewImage(q); var mywatch = new Stopwatch(); mywatch.Start(); var results = opts.Segm == Options.SegmentationType.SegmBased ? Retrieval.SearchSegmBased(queryimg, Dataset) : Retrieval.SearchSegmFree(queryimg, Dataset); mywatch.Stop(); ProgressBar.Add(ref duration, mywatch.Elapsed.TotalSeconds); //add the results to the final xml file concurrentGtRels.Add(new VCGXMLFormat.RelevanceListings.rel { queryid = Path.GetFileNameWithoutExtension(q), words = results.Select(r => new VCGXMLFormat.QueryRelevanceJudgements.Rels { documentName = r.Document, x = r.X, y = r.Y, width = r.Width, height = r.Height, similarity = r.Similarity }).ToList() }); myProgressBar.Increase(100d / queries.Length); }); totalDuration.Stop(); hKws14XMLFormat.gtrels = concurrentGtRels.ToList(); //write the xml file and output the query time Console.WriteLine("Done!"); Console.WriteLine($"Average Time per Query: {(duration / queries.Length).ToString("0.00")} sec"); Console.WriteLine($"Total Time: {totalDuration.Elapsed.TotalSeconds.ToString("0.00")}"); Console.WriteLine("Writing the output xml file..."); try { VCGXMLFormat.serializeToXML(hKws14XMLFormat, opts.OutXMLResults); } catch { Console.WriteLine("ERROR saving the xml file to the defined output name. I will try to save the result to the file: default.xml at the current directory."); VCGXMLFormat.serializeToXML(hKws14XMLFormat, "default.xml"); } return(true); }, (DescriptorOptions Options) => { string imagebase64 = Options.ImageBase64 ?? Console.ReadLine(); if (string.IsNullOrEmpty(imagebase64)) { Error("Need to supply image base64 encoding through argument or standard input stream"); } var arrayString = Retrieval.GetDescriptor(imagebase64) .Select(x => Convert.ToString(x, CultureInfo.InvariantCulture)); Console.WriteLine( string.Join("@", arrayString) ); return(true); }, (SearchOptions Options) => { float[] documentDescriptors = Options.DocumentDescriptorFloatVector ?? Options.GetFloatVectors(Console.ReadLine()); if (documentDescriptors == null) { Error("Need to supply document descriptors through argument or standard input stream"); } if (Options.QueryDescriptorFloatVector == null) { Error("Need to supply query descriptors through argument"); } Console.WriteLine( string.Join("@", Retrieval.Search( Options.QueryDescriptorFloatVector, Options.QueryWidth, Options.QueryHeight, documentDescriptors ) ) ); return(true); }, err => false); //Console.ReadKey(); Console.WriteLine(); }