コード例 #1
0
        private async void chooseImage(object sender, RoutedEventArgs e)
        {
            var customFileType =
                new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
            {
                { DevicePlatform.Android, new string[] { "image/png", "image/jpeg" } },
                { DevicePlatform.UWP, new string[] { ".jpg", ".png" } }
            });
            var options = new PickOptions
            {
                PickerTitle = "Pilih Gambar..",
                FileTypes   = customFileType,
            };
            var result = await FilePicker.PickAsync(options);

            byte[] hasil;
            if (result != null)
            {
                Stream stream = await result.OpenReadAsync();

                using (var streamReader = new MemoryStream())
                {
                    stream.CopyTo(streamReader);
                    hasil = streamReader.ToArray();
                }
                string fileName = result.FileName;
                imageLaporan             = new UploadedImage(fileName, hasil, 0);
                txtNamaFile.Text         = fileName;
                gridFile.Visibility      = Visibility.Visible;
                txtStatusFile.Visibility = Visibility.Collapsed;
            }
        }
コード例 #2
0
        public IActionResult Post([FromForm] UploadedImage uploadedFile)
        {
            string imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images");
            string imageName = DateTime.Now.ToString("yyyyMMddHHmmss") + uploadedFile.Image.FileName;

            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }

            try
            {
                using (FileStream fileStream = System.IO.File.Create(Path.Combine(imagePath, imageName)))
                {
                    uploadedFile.Image.CopyTo(fileStream);
                    fileStream.Flush();
                }
                var classifier = new Classifier();
                var result     = classifier.Classify(imagePath, imageName);

                return(File(result, "image/jpeg"));
            }
            catch (Exception ex)
            {
                return(Content(ex.Message.ToString()));
            }
            finally
            {
                System.IO.File.Delete(Path.Combine(imagePath, imageName));
            }
        }
コード例 #3
0
 public ImageViewModel(UploadedImage image)
 {
     this.Id            = image.Id;
     this.ImgUrl        = image.ThumbnailSrc;
     this.LikesCount    = image.LikesCount;
     this.CommentsCount = image.Comments.Count();
 }
コード例 #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string         routeName = Request.QueryString["Route"];
        UploadedImages list      = UploadedImages.FromSession(routeName);

        string temporaryFolder = PathFunctions.GetTempPath();

        for (int i = 0; i < Request.Files.Count; i++)
        {
            try
            {
                HttpPostedFile file = Request.Files[i];

                //creo un nuovo file in session
                string filePath = Path.Combine(temporaryFolder,
                                               string.Format("{0}-{1}.jpg", (list.Count + 1).ToString("000"), routeName));
                UploadedImage ui = new UploadedImage(filePath, file.InputStream);
                if (string.IsNullOrEmpty(ui.Description))
                {
                    ui.Description = Path.GetFileNameWithoutExtension(file.FileName);
                }
                list.Add(ui);
            }
            catch
            {
                //file non valido, mancato upload!
            }
        }
    }
コード例 #5
0
        public ActionResult Upload(UploadedImage uploadimage)
        {
            HttpPostedFileBase file = Request.Files["ImageUpload"];

            uploadimage.ImageId = Guid.NewGuid();

            if (file != null && file.FileName != null && file.FileName != "")
            {
                FileInfo fi = new FileInfo(file.FileName);
                if (fi.Extension != ".jpeg" && fi.Extension != ".jpg" && fi.Extension != ".png")
                {
                    TempData["Errormsg"] = "Image File Extension is Not valid";
                    return(View(uploadimage));
                }
                else
                {
                    uploadimage.ImageUpload = uploadimage.ImageId + fi.Extension;

                    file.SaveAs(Server.MapPath("~/Content/Image/" + uploadimage.ImageId + fi.Extension));
                }
            }
            using (ImageUploadsEntities1 db = new ImageUploadsEntities1())
            {
                db.UploadedImages.Add(uploadimage);
                db.SaveChanges();
                return(RedirectToAction("Gallery"));
            }
        }
コード例 #6
0
ファイル: UploadFile.aspx.cs プロジェクト: jbvios/mtbscout
    protected void Page_Load(object sender, EventArgs e)
    {
        string routeName = Request.QueryString["Route"];
        UploadedImages list = UploadedImages.FromSession(routeName);

        string temporaryFolder = PathFunctions.GetTempPath();

        for (int i = 0; i < Request.Files.Count; i++)
        {
            try
            {
                HttpPostedFile file = Request.Files[i];

                //creo un nuovo file in session
                string filePath = Path.Combine(temporaryFolder,
                    string.Format("{0}-{1}.jpg", (list.Count + 1).ToString("000"), routeName));
                UploadedImage ui = new UploadedImage(filePath, file.InputStream);
                list.Add(ui);
            }
            catch
            {
                //file non valido, mancato upload!
            }
        }
    }
コード例 #7
0
    void tb_TextChanged(object sender, EventArgs e)
    {
        TextBox       tb = ((TextBox)sender);
        UploadedImage ui = descriptionMap[tb];

        ui.Description = tb.Text;
    }
コード例 #8
0
        public async Task <UploadedImage> AddImageAsync(Stream stream, string originalName, string userName)
        {
            await InitializeResourcesAsync();

            string uploadId      = Guid.NewGuid().ToString();
            string fileExtension = originalName.Substring(originalName.LastIndexOf('.'));
            string fileName      = ImagePrefix + uploadId + fileExtension;
            string userHash      = userName.GetHashCode().ToString();

            var imageBlob = _uploadContainer.GetBlockBlobReference(fileName);
            await imageBlob.UploadFromStreamAsync(stream);

            var img = new UploadedImage
            {
                Id         = uploadId,
                FileName   = fileName,
                ImagePath  = imageBlob.Uri.ToString(),
                UploadTime = DateTime.Now,
                UserHash   = userHash
            };

            await _dbContext.Images.AddAsync(img);

            await _dbContext.SaveChangesAsync();

            return(img);
        }
コード例 #9
0
        public static void SeedMigrateDatabase(DatabaseContext appContext)
        {
            appContext.Database.Migrate();
            var defaultProfileImage = appContext.Images.FirstOrDefault(i => i.ExternalId == "default-profile-image");

            if (defaultProfileImage == null)
            {
                defaultProfileImage = new UploadedImage
                {
                    ExternalId = "default-profile-image",
                    MediaType  = "image/png",
                    FilePath   = "default-profile-image.png"
                };
                appContext.Images.Add(defaultProfileImage);
                appContext.SaveChanges();
            }

            foreach (var sectionName in _sectionNames)
            {
                var section = appContext.Sections.FirstOrDefault(s => s.Name == sectionName);
                if (section != null)
                {
                    continue;
                }

                section = new Section
                {
                    Name = sectionName
                };
                appContext.Sections.Add(section);
                appContext.SaveChanges();
            }
        }
コード例 #10
0
        public async Task <IEnumerable <UploadedImage> > GetImagesAsync()
        {
            await InitializeResourcesAsync();

            var imageList = new List <UploadedImage>();

            foreach (BlobItem blob in _watermarkContainer.GetBlobs(prefix: ImagePrefix))
            {
                var blobClient = _watermarkContainer.GetBlobClient(blob.Name);
                var image      = new UploadedImage {
                    ImagePath = blobClient.Uri.ToString()
                };
                imageList.Add(image);
            }

            // OLD SDK
            //var token = new BlobContinuationToken();
            //var blobList = await _publicContainer.ListBlobsSegmentedAsync(ImagePrefix, true, BlobListingDetails.All, 100, token, null, null);

            //foreach (var blob in blobList.Results)
            //{
            //    var image = new UploadedImage
            //    {
            //        ImagePath = blob.Uri.ToString()
            //    };

            //    imageList.Add(image);
            //}

            return(imageList);
        }
コード例 #11
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (UploadedImage != null)
            {
                var file = "./wwwroot/img/" + UploadedImage.FileName;
                using (var fileStream = new FileStream(file, FileMode.Create))
                {
                    await UploadedImage.CopyToAsync(fileStream);
                }
            }

            Blog blog = new Blog();

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            blog.Date   = DateTime.Now;
            blog.Header = Header;
            blog.Text   = Text;
            blog.Image  = UploadedImage != null ? UploadedImage.FileName : "";
            blog.UserId = userId;

            _context.Blog.Add(blog);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
コード例 #12
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            setComboBoxKategoriLostFound();
            var entry = this.Frame.BackStack.LastOrDefault();

            if (entry.SourcePageType == typeof(ConfirmReportPage))
            {
                isChosen = true;
                ConfirmReportParams param = session.getConfirmReportParams();
                txtJudulLaporan.Text        = param.judul_laporan;
                txtDescBarang.Text          = param.deskripsi_laporan;
                txtAutocompleteAddress.Text = param.alamat_laporan;
                lat          = param.lat_laporan;
                lng          = param.lng_laporan;
                imageLaporan = param.image_laporan;
                cbJenisBarang.SelectedIndex = param.combo_box_selected_index;
                if (imageLaporan != null)
                {
                    txtNamaFile.Text         = imageLaporan.file_name;
                    gridFile.Visibility      = Visibility.Visible;
                    txtStatusFile.Visibility = Visibility.Collapsed;
                }
                this.Frame.BackStack.RemoveAt(this.Frame.BackStack.Count - 1);
            }
        }
コード例 #13
0
        public ServiceResponse <UploadedImage> AddImage(UploadedImage image)
        {
            var response = new ServiceResponse <UploadedImage>();

            imageRepository.Insert(image);
            response.Result = image;
            return(response);
        }
コード例 #14
0
        private async Task UploadImageToFileSystemAsync(string newImagePath)
        {
            var file = Path.Combine(environment.WebRootPath, newImagePath);

            using (var fileStream = new FileStream(file, FileMode.Create))
            {
                await UploadedImage.CopyToAsync(fileStream);
            }
        }
コード例 #15
0
ファイル: MediaLarge.cs プロジェクト: Z19-House/ThreeMen
 public static MediaLarge FromUploadedImage(UploadedImage uploadedImage, string imageServer)
 {
     return(new MediaLarge
     {
         Hash = uploadedImage.Hash,
         ResUri = uploadedImage.FileName.AddServerAddress(imageServer),
         ResType = ResType.Image,
         UploadTime = uploadedImage.UploadTime
     });
 }
コード例 #16
0
ファイル: HomeController.cs プロジェクト: 14bd02002/cloud2
        public async Task <ActionResult> Upload(FormCollection formCollection)
        {
            var model = new UploadedImage();

            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["uploadedFile"];
                model = await _imageService.CreateUploadedImage(file);
            }
            return(View("Index", model));
        }
コード例 #17
0
 public PostDetailsViewModel(UploadedImage image)
 {
     this.Id                = image.Id;
     this.ImgUrl            = image.OriginalSrc;
     this.UploaderId        = image.UploaderId;
     this.UploaderUsername  = image.Uploader.Username;
     this.UploaderAvatarUrl = image.Uploader.AvatarUrl;
     this.LikesCount        = image.LikesCount;
     this.ImgDescription    = image.Description;
     this.Comments          = image.Comments.Select(c => new ImageCommentViewModel(c)).ToList();
 }
コード例 #18
0
        private async Task <int> StoreImageInDb(ApnaBawarchiKhanaDbContext dbContext, byte[] imageData)
        {
            var imData = new UploadedImage {
                ImageData = imageData
            };
            var uploadedImage = await dbContext.UploadedImages.AddAsync(imData);

            await dbContext.SaveChangesAsync();

            return(uploadedImage.Entity.Id);
        }
コード例 #19
0
ファイル: StorageService.cs プロジェクト: frankibem/UniWatch
        /// <summary>
        /// Deletes a stored image
        /// </summary>
        /// <param name="image">The image to delete</param>
        public void DeleteImage(UploadedImage image)
        {
            if (image == null)
            {
                return;
            }

            CloudBlockBlob imageBlob = _container.GetBlockBlobReference(image.BlobName);

            Task.Run(() => imageBlob.DeleteIfExistsAsync()).Wait();
        }
コード例 #20
0
        public async Task AddImageToBlobStorageAsync(UploadedImage image)
        {
            //  get the container reference
            var container = GetImagesBlobContainer();
            // using the container reference, get a block blob reference and set its type
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(image.Name);

            blockBlob.Properties.ContentType = image.ContentType;
            // finally, upload the image into blob storage using the block blob reference
            var fileBytes = image.Data;
            await blockBlob.UploadFromByteArrayAsync(fileBytes, 0, fileBytes.Length);
        }
コード例 #21
0
        public async Task <ServiceResult <SavedImage, SaveImageError> > SaveImageAsync(string filePath, Stream imageStream)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return(ServiceResult <SavedImage, SaveImageError> .CreateFailed(SaveImageError.EmptyFilePath));
            }

            if (imageStream.Length > _imageStorageConfiguration.MaximumImageSize)
            {
                return(ServiceResult <SavedImage, SaveImageError> .CreateFailed(SaveImageError.TooBigImage));
            }

            var imageExtension     = Path.GetExtension(filePath);
            var mediaType          = MimeMapping.MimeUtility.GetMimeMapping(filePath);
            var isMediaTypeAllowed = _imageStorageConfiguration.AllowedImageMediaTypes.Any(t => t == mediaType);

            if (!isMediaTypeAllowed)
            {
                return(ServiceResult <SavedImage, SaveImageError> .CreateFailed(SaveImageError.NotAllowedMediaType));
            }
            var externalId        = Guid.NewGuid().ToString();
            var uploadedImageName = $"{externalId}{imageExtension}";

            var firebaseStorage = new FirebaseStorage(_firebaseImageStorageConfiguration.StorageBucket)
                                  .Child(_firebaseImageStorageConfiguration.ImagesDirectory)
                                  .Child(uploadedImageName);

            string downloadUri;

            try
            {
                downloadUri = await firebaseStorage.PutAsync(imageStream);
            }
            catch (FirebaseStorageException)
            {
                return(ServiceResult <SavedImage, SaveImageError> .CreateFailed(SaveImageError.StorageError));
            }

            var uploadedImage = new UploadedImage
            {
                FilePath   = downloadUri,
                ExternalId = externalId,
                MediaType  = mediaType
            };

            var imagesRepository = _unitOfWork.GetRepository <UploadedImage>();

            imagesRepository.Create(uploadedImage);
            await _unitOfWork.SaveAsync();

            return(ServiceResult <SavedImage, SaveImageError> .CreateSuccess(new SavedImage(uploadedImage.ExternalId)));
        }
コード例 #22
0
 public void LoadData(PromotionEntity p)
 {
     if (!IsPostBack)
     {
         promotionID.Value        = p.ID;
         title.Value              = p.Title;
         shortdescription.Value   = p.ShortDiscription;
         discription.Value        = p.Discription;
         ddlStatus.SelectedValue  = p.StatusID.ToString();
         UploadedImage.DefaultUrl = p.Image;
         UploadedImage.DataBind();
     }
 }
コード例 #23
0
ファイル: StorageService.cs プロジェクト: frankibem/UniWatch
        /// <summary>
        /// Downloads the given image to a stream
        /// </summary>
        /// <param name="image">The image to download</param>
        /// <returns>A memory stream with the downloaded image</returns>
        public async Task <MemoryStream> DownloadImage(UploadedImage image)
        {
            if (image == null)
            {
                return(null);
            }

            var            result    = new MemoryStream();
            CloudBlockBlob imageBlob = _container.GetBlockBlobReference(image.BlobName);
            await imageBlob.DownloadToStreamAsync(result);

            return(result);
        }
コード例 #24
0
        public IActionResult Upload()
        {
            if (userManager.GetUserId(HttpContext.User) == null)
            {
                return(Redirect("/Identity/Account/Login"));
            }

            var model = new UploadedImage()
            {
                access = "public"
            };

            return(View(model));
        }
コード例 #25
0
        PromotionEntity GetPromotion()
        {
            PromotionEntity p = new PromotionEntity();

            p.ID               = promotionID.Value;
            p.Title            = title.Value;
            p.ShortDiscription = shortdescription.Value;
            p.Discription      = discription.Value;
            p.Image            = UploadedImage.GetUrl();
            p.Status           = StatusBus.Instance.GetStatus(int.Parse(ddlStatus.SelectedValue));
            p.CreatedDate      = DateTime.Now;
            p.CreatedBy        = UserBus.Instance.GetUser(User.Identity.Name);
            return(p);
        }
コード例 #26
0
        public static async Task RecordImageUploadedAsync(ApplicationDbContext dbContext, string uploadId, string fileName, string imageUri, string userHash = null)
        {
            var img = new UploadedImage
            {
                Id         = uploadId,
                FileName   = fileName,
                ImagePath  = imageUri,
                UploadTime = DateTime.Now,
                UserHash   = userHash
            };

            await dbContext.Images.AddAsync(img);

            await dbContext.SaveChangesAsync();
        }
コード例 #27
0
 public ConfirmReportParams(string tag_laporan, string judul_laporan, string jenis_laporan, string deskripsi_laporan, string lat_laporan, string lng_laporan, string alamat_laporan, int id_kecamatan, string tanggal_laporan, string waktu_laporan, SettingKategori kategori_selected, int combo_box_selected_index, UploadedImage image_laporan)
 {
     this.tag_laporan              = tag_laporan;
     this.judul_laporan            = judul_laporan;
     this.jenis_laporan            = jenis_laporan;
     this.deskripsi_laporan        = deskripsi_laporan;
     this.lat_laporan              = lat_laporan;
     this.lng_laporan              = lng_laporan;
     this.tanggal_laporan          = tanggal_laporan;
     this.alamat_laporan           = alamat_laporan;
     this.id_kecamatan             = id_kecamatan;
     this.waktu_laporan            = waktu_laporan;
     this.kategori_selected        = kategori_selected;
     this.combo_box_selected_index = combo_box_selected_index;
     this.image_laporan            = image_laporan;
 }
コード例 #28
0
        public void UploadedImagesCollection_ShouldBeSetAndGottenCorrectly(int imageId)
        {
            var image = new UploadedImage()
            {
                Id = imageId
            };
            var set = new List <UploadedImage> {
                image
            };

            var user = new RegularUser {
                UploadedImages = set
            };

            Assert.AreEqual(user.UploadedImages.First().Id, imageId);
        }
コード例 #29
0
        public void UploadImage(string ImgTitle, string thumbnailImgUrl, string originalImgUrl, RegularUser uploader)
        {
            var image = new UploadedImage()
            {
                Title        = ImgTitle,
                ThumbnailSrc = thumbnailImgUrl,
                OriginalSrc  = originalImgUrl,
                DateUploaded = DateTime.Now,
                IsDeleted    = false
            };

            using (var uow = this.uow)
            {
                uploader.UploadedImages.Add(image);
                uow.SaveChanges();
            }
        }
コード例 #30
0
 protected override void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             UploadedImage?.Dispose();
             int c = UploadedFiles.Count;
             for (int i = 0; i < c; i++)
             {
                 UploadedFiles[i]?.FileStreamContent?.Dispose();
             }
         }
         disposedValue = true;
         base.Dispose(disposing);
     }
 }
コード例 #31
0
        public async Task <IEnumerable <UploadedImage> > GetImagesAsync()
        {
            var imageList = new List <UploadedImage>();
            var files     = await Task.Run(() => Directory.EnumerateFiles(ImageFolder));

            foreach (var file in files)
            {
                var image = new UploadedImage
                {
                    ImagePath = ImageFolderUri + "/" + Path.GetFileName(file)
                };

                imageList.Add(image);
            }

            return(imageList);
        }
コード例 #32
0
ファイル: EditRoute.aspx.cs プロジェクト: jbvios/mtbscout
 public MyRadioButton(UploadedImage image)
 {
     this.AutoPostBack = false;
     this.GroupName = "MainImage";
     this.image = image;
 }
コード例 #33
0
ファイル: EditRoute.aspx.cs プロジェクト: jbvios/mtbscout
 public MyImageButton(UploadedImage image)
 {
     this.image = image;
 }