public void AttachOrReplaceCoverImage_WithNewCoverImage_AndExistingCoverImage_ReplacesExistingCoverImage() { // Arrange var image = new Image(); var song = new Song { CoverImageId = image.Id, CoverImage = image }; var fileInfo = new FileInfo("contentType", new byte[] { 1, 2, 3, 4 }); _imageService.AddImage(fileInfo).Returns(new Image()); // Act song.AttachOrReplaceCoverImage(fileInfo, _imageService); // Assert Assert.That(song.CoverImageId, Is.Not.Null); Assert.That(song.CoverImage, Is.Not.Null); Assert.That(song.CoverImageId, Is.Not.EqualTo(image.Id)); _imageService.Received(1).RemoveImage(image); _imageService.Received(1).AddImage(fileInfo); }
public IActionResult Post(long UserId) { var file = Request.Form.Files[0]; if (file.Length > 0) { using (var reader = new BinaryReader(file.OpenReadStream())) { //string contentAsString = reader.ReadToEnd(); //byte[] ImageData = new byte[contentAsString.Length * sizeof(char)]; //Buffer.BlockCopy(contentAsString.ToCharArray(), 0, ImageData, 0, ImageData.Length); byte[] ImageData = null; ImageData = reader.ReadBytes((int)file.Length); imageService.AddImage(UserId, ImageData, out string ErrorMessage); if (ErrorMessage != "") { Debug.WriteLine(ErrorMessage); return(BadRequest(ErrorMessage)); } ErrorMessage = "Изображение добавлено успешно"; return(Ok(ErrorMessage)); } } return(BadRequest()); }
public ImageResponseModel AddImage(ImageRequestModel image) { var imgId = _imageService.AddImage(image.name, image.type, image.data); var imgResponse = new ImageResponseModel { imageId = imgId }; return(imgResponse); }
public void AttachOrReplaceCoverImage(FileInfo file, IImageService imageService) { RemoveCoverImage(imageService); if (file != null) { CoverImage = imageService.AddImage(file); CoverImageId = CoverImage.Id; } }
public ActionResult UploadImageForEdit(int AdId) { int id = User.Identity.GetUserId <int>(); string idPath = id.ToString(); string imagePath = @"~\Images"; string fullPath = Path.Combine(imagePath, idPath); string imagePathForSave = @"..\..\Images"; string fullPathForSave = Path.Combine(imagePathForSave, idPath); var configImageAdd = new MapperConfiguration(cfg => { cfg.CreateMap <ImageVM, ImageDTO>(); }); configImageAdd.AssertConfigurationIsValid(); var mapperImageAdd = configImageAdd.CreateMapper(); foreach (string file in Request.Files) { var upload = Request.Files[file]; if (upload != null) { // получаем имя файла string fileName = Path.GetFileName(upload.FileName); // сохраняем файл в папку Files в проекте string saveImage = Path.Combine(fullPath, fileName); upload.SaveAs(Server.MapPath(saveImage)); //формируем путь для сохранения в БД string fullPathImageForSave = Path.Combine(fullPathForSave, fileName); //Сохраняем в БД ImageVM newImage = new ImageVM(); newImage.Name = fileName; newImage.PathToOriginal = fullPathImageForSave; newImage.PathToSmall = fullPathImageForSave; newImage.AdId = AdId; var image = mapperImageAdd.Map <ImageVM, ImageDTO>(newImage); imageService.AddImage(image); } } //Получаем обновленный список изображений var configImageGet = new MapperConfiguration(cfg => { cfg.CreateMap <ImageDTO, ImageVM>(); }); configImageGet.AssertConfigurationIsValid(); var mapperImageGet = configImageGet.CreateMapper(); var images = mapperImageGet.Map <IEnumerable <ImageDTO>, IEnumerable <ImageVM> >(imageService.GetImagesByAd(AdId)); imageService.Dispose(); return(View("ImageDelete", images)); }
public void Post([FromBody] Image image) { if (ModelState.IsValid) { _services.AddImage(image); } else { BadRequest(ModelState); } }
public async Task IdentifyObjects(IFormFile imageFile, Guid id) { try { MemoryStream imageMemoryStream = new MemoryStream(); await imageFile.CopyToAsync(imageMemoryStream); //Check that the image is valid byte[] imageData = imageMemoryStream.ToArray(); //Convert to Image Image image = Image.FromStream(imageMemoryStream); string fileName = string.Format("{0}.Jpeg", image.GetHashCode()); string imageFilePath = Path.Combine(_imagesTmpFolder, fileName); //// bool exists = System.IO.Directory.Exists(_imagesTmpFolder); if (!exists) { System.IO.Directory.CreateDirectory(_imagesTmpFolder); } //save image to a path image.Save(imageFilePath, ImageFormat.Jpeg); /// //Convert to Bitmap Bitmap bitmapImage = (Bitmap)image; //Measure execution time var watch = System.Diagnostics.Stopwatch.StartNew(); //Set the specific image data into the ImageInputData type used in the DataView ImageInputData imageInputData = new ImageInputData { Image = bitmapImage }; //Detect the objects in the image var result = DetectAndPaintImage(imageInputData, imageFilePath); //Stop measuring time watch.Stop(); elapsedMs = watch.ElapsedMilliseconds; result.ElapsedTime = elapsedMs; result.imageStringOriginal = imageData; await _imageService.AddImage(id, result); } catch (Exception e) { throw new Exception(e.Message); } }
public IHttpActionResult PostImage([FromBody] ImagePostModel image) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } int?profileId = GetProfileId(); if (profileId == null) { return(new HttpActionResult(HttpStatusCode.NotFound, "User has no profile")); } HashSet <int> hashTags = _hashTagService.PutHashTagsByName (new HashSet <string>(image.HashTags)); ImageDTO imageDTO = new ImageDTO { ImageFileId = image.FileId, Title = image.Title, ProfileId = profileId.Value }; int id = _imageService.AddImage(imageDTO, hashTags); return(Ok(id)); }
public async Task <IActionResult> Create([FromForm] ImageViewModel imageVm) { var webRootPath = _hostingEnvironment.WebRootPath; var result = await DirectoryManager.SaveFileInFolder(webRootPath, _defaultFolderForUploadImages, imageVm); if (result == null) { throw new ApiException(System.Net.HttpStatusCode.InternalServerError); } await _imageService.AddImage(imageVm); return(Ok()); }
public IHttpActionResult Post([FromBody] string imageUrl) { try { var identity = (ClaimsIdentity)User.Identity; string accountId = identity.Claims.FirstOrDefault(c => c.Type.Equals("AccountId")).Value; _imageService.AddImage(accountId, imageUrl); return(Ok("Add Image Success")); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); return(BadRequest("Add Image Failed")); } }
public ActionResult AddImage(AddImageModel model, int albumId) { byte[] array = null; if (model.Files.Length > 0) { foreach (var file in model.Files) { if (file != null) { var tagsDto = new List <TagDTO>(); using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); array = ms.GetBuffer(); } if (!string.IsNullOrWhiteSpace(model.Tags)) { foreach (var el in model.Tags.Split(' ')) { tagsDto.Add(new TagDTO() { Name = el.Trim() }); } } try { imageService.AddImage(new PictureDTO() { Img = array, Tags = tagsDto, AlbumId = albumId }); } catch (TargetNotFoundException) { return(new HttpNotFoundResult()); } } } } return(Redirect($"/Images/Index?albumId={albumId}")); }
protected int UploadImage(IImageService imageService, HttpPostedFileBase file) { var fileName = Path.GetFileName(file.FileName); string filePath = Define.ImageSavePath + Guid.NewGuid().ToString() + "/"; if (!Directory.Exists(Server.MapPath(filePath))) { Directory.CreateDirectory(Server.MapPath(filePath)); } var path = Path.Combine(Server.MapPath(filePath), fileName); file.SaveAs(path); var imageModel = new ImageProductViewModel { ImageName = file.FileName, ImagePath = Path.Combine(filePath, fileName) }; return(imageService.AddImage(imageModel)); }
public void AddImage_AddsANewImage() { // Arrange var fileInfo = new FileInfo("contentType", new byte[] { 1, 2, 3, 4 }); _imageRepository.Create().Returns(new Image()); _fileRepository.Create().Returns(new File()); // Act var image = _imageService.AddImage(fileInfo); // Assert Assert.That(image.ContentType, Is.EqualTo(fileInfo.ContentType)); Assert.That(image.ContentLength, Is.EqualTo(4)); Assert.That(image.File, Is.Not.Null); Assert.That(image.File.Data, Is.EqualTo(fileInfo.ToByteArray())); Assert.That(image.FileId, Is.EqualTo(image.File.Id)); _imageRepository.Received(1).Create(); _imageRepository.Received(1).Add(image); _fileRepository.Received(1).Create(); _fileRepository.Received(1).Add(image.File); }
public async Task <IActionResult> AddImage(AddImageViewModel input, IFormFile Picture) { if (!ModelState.IsValid) { return(this.View(input)); } if (Picture == null) { ModelState.AddModelError(string.Empty, "Picture is required"); return(this.View(input)); } input.PhotographyAddictedUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var imageId = await imageService.AddImage(input, Picture); if (imageId == 0) { ModelState.AddModelError(string.Empty, "Picture is bigger than 256kb"); return(this.View(input)); } return(RedirectToAction("PreviewUser", "Users", new { Id = input.PhotographyAddictedUserId })); }
public async Task <IActionResult> AddImage([FromBody] AddImageModel model) { await _imageService.AddImage(model.Name, model.ImageUrl); return(Ok()); }
public HttpResponseMessage UploadImage() { var httpRequest = HttpContext.Current.Request; HttpPostedFile file = null; if (httpRequest.Files.Count > 0) { file = httpRequest.Files.Get("File"); } if (file == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File was not chosen")); } if (!file.ContentType.Contains("image")) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unsupported media type")); } if (!(file.ContentLength > 0)) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File is empty")); } string description = httpRequest.Params.Get("Description"); List <string> tagsArray = httpRequest.Params.GetValues("Tags")?.ToList(); if (tagsArray != null) { var tagRegex = tagsArray.All(p => { return(Regex.IsMatch(p, @"^\w*$")); }); if (tagRegex == false) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Tag should contain only alphanumeric values and should not contain white spaces")); } } byte[] image = null; using (var binaryReader = new BinaryReader(file.InputStream)) { image = binaryReader.ReadBytes(file.ContentLength); } UploadedImage uploadedImage = new UploadedImage { Buffer = image, Description = description, Tags = tagsArray, FileName = file.FileName, UserId = HttpContext.Current.User.Identity.GetUserId(), }; try { imageService.AddImage(uploadedImage); return(Request.CreateResponse(HttpStatusCode.OK, "Photo uploaded successfully")); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } }