Esempio n. 1
0
        public async Task OnPostAsync()
        {
            Message = "LOADING...";


            string assetsRelativePath = @"../../../assets";
            string assetsPath         = GetAbsolutePath(assetsRelativePath);


            var imagesFolder       = Path.Combine(assetsPath, "inputs", "images-for-predictions", "tmp-web-image");
            var imageClassifierZip = Path.Combine(assetsPath, "inputs", "MLNETModel", "imageClassifier.zip");

            imagesFolder += @"/" + ImageFile.FileName;

            try
            {
                using (var stream = System.IO.File.Create(imagesFolder))
                {
                    await ImageFile.CopyToAsync(stream);
                }


                var modelScorer = new ModelScorer(imagesFolder, imageClassifierZip);
                Predict = modelScorer.ClassifySingleImage();
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }

            Message = "...";
            //return RedirectToPage("./Index");
        }
Esempio n. 2
0
        public void Create()
        {
            var hostingEnvironment = Startup.AutofacContainer.Resolve <IWebHostEnvironment>();

            string wwwRootpath = hostingEnvironment.WebRootPath;
            string fileName    = Path.GetFileNameWithoutExtension(ImageFile.FileName);
            string extension   = Path.GetExtension(ImageFile.FileName);

            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            string path = Path.Combine(wwwRootpath + "/images/", fileName);

            var stream = new FileStream(path, FileMode.Create);

            ImageFile.CopyToAsync(stream);

            var blogCompose = new BlogComposes()
            {
                Title      = this.Title,
                Body       = this.Body,
                ImageUrl   = fileName,
                Date       = this.DateTime,
                CategoryId = this.CategoryId
            };

            _blogComposeService.CreateCompose(blogCompose);
        }
Esempio n. 3
0
        //public void OnGet()
        //{

        //}

        public async Task <IActionResult> OnPostAsync()
        {
            // Show image on web page
            var imageFilePath = Path.Combine(_host.WebRootPath, "images\\uploadedImage.png");

            using (var fileStream = new FileStream(imageFilePath, FileMode.OpenOrCreate))
            {
                await ImageFile.CopyToAsync(fileStream);
            }
            ImageFileUrl = "/images/uploadedImage.png";

            // Post image to Custom Vision, get resut and show on web page
            var cvClient = new CustomVisionPredictionClient()
            {
                Endpoint = cvEndpoint,
                ApiKey   = cvPredictionKey
            };

            try
            {
                var cvResult = await cvClient.DetectImageAsync(
                    Guid.Parse(cvProjectId), cvPublishName, ImageFile.OpenReadStream());

                if (cvResult.Predictions.Count > 0)
                {
                    Result      = "結果:";
                    Predictions = cvResult.Predictions;

                    // Draw rectangle on detected image
                    var detectedImagePath  = Path.Combine(_host.WebRootPath, "images\\detectedImage.png");
                    var rectangleImagePath = Path.Combine(_host.WebRootPath, "images\\rectangle.png");

                    using (var detectedImage = new Bitmap(imageFilePath))
                        using (var graphics = Graphics.FromImage(detectedImage))
                        {
                            graphics.DrawImage(new Bitmap(rectangleImagePath),
                                               (int)(cvResult.Predictions[0].BoundingBox.Left * detectedImage.Width),
                                               (int)(cvResult.Predictions[0].BoundingBox.Top * detectedImage.Height),
                                               (int)(cvResult.Predictions[0].BoundingBox.Width * detectedImage.Width),
                                               (int)(cvResult.Predictions[0].BoundingBox.Height * detectedImage.Height));

                            detectedImage.Save(detectedImagePath, ImageFormat.Png);
                        }

                    ImageFileUrl = "/images/detectedImage.png";
                }
                else
                {
                    Result = "判定できませんでした";
                }
            }
            catch (CustomVisionErrorException e)
            {
                Result = "エラー: " + e.Message;
            }

            return(Page());
        }
Esempio n. 4
0
        //public void OnGet()
        //{

        //}

        public async Task <IActionResult> OnPostAsync()
        {
            // Show image on web page
            var imageFilePath = Path.Combine(_host.WebRootPath, "images\\uploadedImage.png");

            using (var fileStream = new FileStream(imageFilePath, FileMode.OpenOrCreate))
            {
                await ImageFile.CopyToAsync(fileStream);
            }
            ImageFileUrl = "/images/uploadedImage.png";

            // Post image to Custom Vision, get resut and show on web page
            var faceClient = new FaceClient(new ApiKeyServiceClientCredentials(faceSubscriptionKey))
            {
                Endpoint = faceEndpoint
            };
            var faceAttibute = new FaceAttributeType[] { FaceAttributeType.Emotion };

            try
            {
                var faceResult = await faceClient.Face.DetectWithStreamAsync(
                    ImageFile.OpenReadStream(), false, false, faceAttibute);

                if (faceResult.Count > 0)
                {
                    Result  = "結果:";
                    Emotion = faceResult[0].FaceAttributes.Emotion;
                }
                else
                {
                    Result = "判定できませんでした";
                }

                // Draw rectangle on detected image
                var detectedImagePath  = Path.Combine(_host.WebRootPath, "images\\detectedImage.png");
                var rectangleImagePath = Path.Combine(_host.WebRootPath, "images\\rectangle.png");

                using (var detectedImage = new Bitmap(imageFilePath))
                    using (var graphics = Graphics.FromImage(detectedImage))
                    {
                        graphics.DrawImage(new Bitmap(rectangleImagePath),
                                           faceResult[0].FaceRectangle.Left, faceResult[0].FaceRectangle.Top,
                                           faceResult[0].FaceRectangle.Width, faceResult[0].FaceRectangle.Height);
                        detectedImage.Save(detectedImagePath, ImageFormat.Png);
                    }

                ImageFileUrl = "/images/detectedImage.png";
            }
            catch (APIErrorException e)
            {
                Result = "エラー: " + e.Message;
            }

            return(Page());
        }
Esempio n. 5
0
 public async Task <IActionResult> uploadFiles(IFormFile[] files)
 {
     foreach (var ImageFile in files)
     {
         if (ImageFile != null && ImageFile.Length > 0)
         {
             var fileName = Path.GetFileName(ImageFile.FileName);
             var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\img", fileName);
             using (var fileStream = new FileStream(filePath, FileMode.Create))
             {
                 await ImageFile.CopyToAsync(fileStream);
             }
         }
     }
     return(Ok(files.Count()));
 }
Esempio n. 6
0
        public async Task <IActionResult> AddImage(int id)
        {
            if (ImageFile != null)
            {
                using (var stream = new MemoryStream())
                {
                    await ImageFile.CopyToAsync(stream);


                    DbContext.TradeImages.Add(new TradeImage
                    {
                        ImageContent = stream.ToArray(),
                        TradeId      = id
                    });
                }
            }

            await DbContext.SaveChangesAsync();

            return(await OnGet(id));
        }
        /// <summary>
        /// Upload a new image for the given flummery
        /// </summary>
        /// <param name="id">Flummery to be updated</param>
        /// <returns>User should see the same page with the new image displayed</returns>
        public async Task OnPost(int id)
        {
            var item = await _inventory.GetFlummeryBy(id);

            Name = item.Name;
            string fileExt = Path.GetExtension(ImageFile.FileName);

            if (ImageFile != null)
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    await ImageFile.CopyToAsync(memStream);

                    Byte[] imageData = memStream.ToArray();
                    string imageURI  = await _imageService.UploadImage($"{Name}{fileExt}", imageData, ImageFile.ContentType, id);

                    CurrentImgUrl = imageURI;
                    await _imageService.UpdateStoreDbFor(id, imageURI);
                }
            }
        }
        //public void OnGet()
        //{

        //}

        public async Task <IActionResult> OnPostAsync()
        {
            // Show image on web page
            var imageFilePath = Path.Combine(_host.WebRootPath, "images\\uploadedImage.png");

            using (var fileStream = new FileStream(imageFilePath, FileMode.OpenOrCreate))
            {
                await ImageFile.CopyToAsync(fileStream);
            }
            ImageFileUrl = "/images/uploadedImage.png";

            // Post image to Custom Vision, get resut and show on web page
            var cvClient = new CustomVisionPredictionClient()
            {
                Endpoint = cvEndpoint,
                ApiKey   = cvPredictionKey
            };

            try
            {
                var cvResult = await cvClient.ClassifyImageAsync(
                    Guid.Parse(cvProjectId), cvPublishName, ImageFile.OpenReadStream());

                if (cvResult.Predictions.Count > 0)
                {
                    Result      = "結果:";
                    Predictions = cvResult.Predictions;
                }
                else
                {
                    Result = "判定できませんでした";
                }
            }
            catch (CustomVisionErrorException e)
            {
                Result = "エラー: " + e.Message;
            }

            return(Page());
        }
Esempio n. 9
0
        /// <summary>
        /// Post user input to new image & stream image to blob
        /// </summary>
        /// <returns>Redirect to Index page</returns>
        public async Task <IActionResult> OnPostAsync()
        {
            // make call to db w/ ID or create new if ID does not exist
            Image img = await _image.FindImageAsync(ID.GetValueOrDefault()) ?? new Image();

            // set the data from the db to the new data from Image/user input
            img.Name    = Image.Name;
            img.Author  = Image.Author;
            img.Caption = Image.Caption;

            if (ImageFile != null)
            {
                // Do all of our Azure Blob stuff:
                // Get file path & get image on server
                var filePath = Path.GetTempFileName();
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await ImageFile.CopyToAsync(stream);
                }

                // Get container
                var container = await BlobImage.GetContainer("images");

                // Upload the image
                BlobImage.UploadFile(container, ImageFile.FileName, filePath);

                // Get the image we just uploaded
                CloudBlob blob = await BlobImage.GetBlob(ImageFile.FileName, container.Name);

                // Update the db image for the image
                img.URL = blob.Uri.ToString();
            }

            // save the image in the db
            await _image.SaveAsync(img);

            return(RedirectToPage("/Index", new { id = img.ID }));
        }
Esempio n. 10
0
        public async Task <IActionResult> OnPostAsync(ICollection <IFormFile> files, IFormCollection form)
        {
            if (files == null || files.Count == 0)
            {
                Message = "files not selected";
                return(Page());
            }

            string CategoryId = form["CategoryId"];
            string UserEmail  = User.Identity.Name;
            string FolderName = form["FolderName"];

            if (string.IsNullOrEmpty(FolderName))
            {
                FolderName = GetUniqueName("Gal_");
            }
            string imageGallery    = "Gallery";
            string originalGallery = "Original";
            string thumbGallery    = "Thumb";

            var webRoot = _env.WebRootPath;
            var path    = System.IO.Path.Combine(webRoot, imageGallery);

            string uploadResisedPath  = path; //this is where resized images will be stored.
            string uploadOriginalPath = path + "\\" + originalGallery;
            string uploadThumbPath    = path + "\\" + thumbGallery;

            if (!Directory.Exists(uploadResisedPath))
            {
                Directory.CreateDirectory(uploadResisedPath);
            }
            if (!Directory.Exists(uploadOriginalPath))
            {
                Directory.CreateDirectory(uploadOriginalPath);
            }
            if (!Directory.Exists(uploadThumbPath))
            {
                Directory.CreateDirectory(uploadThumbPath);
            }

            foreach (var ImageFile in files)
            {
                if (ImageFile != null) // ImageFile = The IFormFile that was uploaded
                {
                    //var imageName = ImageFile.FileName;
                    string ext = System.IO.Path.GetExtension(ImageFile.FileName).ToLower();

                    string iName = ImageFile.FileName.Replace(ImageFile.FileName, FolderName);
                    iName = iName + ext;

                    var    newImageName = GetUniqueName(iName);
                    string orignalPath  = Path.Combine(uploadOriginalPath, newImageName);
                    string resizedPath  = Path.Combine(uploadResisedPath, newImageName);
                    string thumbPath    = Path.Combine(uploadThumbPath, newImageName);

                    try
                    {
                        using (FileStream fs = new FileStream(orignalPath, FileMode.Create))
                        {
                            await ImageFile.CopyToAsync(fs);
                        }
                        //var image = Image.FromStream(ImageFile.OpenReadStream());
                        Image <Rgba32> image = Image.Load(ImageFile.OpenReadStream());

                        // Get the image's original width and height
                        int originalWidth  = image.Width;
                        int originalHeight = image.Height;
                        int maxSize        = 960;
                        int tSize          = 200;

                        // To preserve the aspect ratio
                        float ratioX = (float)maxSize / (float)originalWidth;
                        float ratioY = (float)maxSize / (float)originalHeight;
                        float ratio  = Math.Min(ratioX, ratioY);

                        float ratioTX = (float)tSize / (float)originalWidth;
                        float ratioTY = (float)tSize / (float)originalHeight;
                        float ratioT  = Math.Min(ratioTX, ratioTY);

                        // New width and height based on aspect ratio
                        int newWidth  = (int)(originalWidth * ratio);
                        int newHeight = (int)(originalHeight * ratio);

                        int    newTWidth  = (int)(originalWidth * ratioT);
                        int    newTHeight = (int)(originalHeight * ratioT);
                        string Format     = "";

                        if (image.Width > image.Height)
                        {
                            Format = "l";
                        }
                        else
                        {
                            Format = "p";
                        }

                        ResizeAndSaveImage(ImageFile.OpenReadStream(), resizedPath, newWidth, newHeight);
                        ResizeAndSaveImage(ImageFile.OpenReadStream(), thumbPath, newTWidth, newTHeight);

                        //save information to the database
                        int ImageId = 0;
                        await this._uploadUnitOfWork.SaveUploadedImages(ImageId, Convert.ToInt32(CategoryId), newImageName, UserEmail, Format, FolderName);
                    }
                    catch (Exception ex)
                    {
                        Message = ex.Message;
                    }
                }
            }

            return(RedirectToPage("Index"));
        }