public IActionResult GetImage(long id)
        {
            ImageDBModel imageDBModel = this.dbContext.ImageDBModels.FirstOrDefault(img => img.Id == id);

            if (imageDBModel == default)
            {
                return(Ok());
            }
            return(File(imageDBModel.Image, "image/jpeg"));
        }
        public async Task <IActionResult> NewImage([FromForm] ImageDTO imageDTO)
        {
            if (new string[] { "item", "avatar" }.Contains(imageDTO.Category) == false)
            {
                return(BadRequest(Models.Response.ErrorResponse("Bad category")));
            }
            //No file | file size > 5MB
            //|| imageDTO.Files.Length > 5242880
            if (imageDTO.Files.Count() < 1)
            {
                return(BadRequest(Models.Response.ErrorResponse("No files")));
            }
            //Wrong image type
            byte imageType = this.GetImageType(imageDTO);

            if (imageType == byte.MaxValue)
            {
                return(BadRequest(Models.Response.ErrorResponse("Bad type")));
            }

            List <Task> fileTasks = new List <Task>();

            foreach (IFormFile file in imageDTO.Files)
            {
                fileTasks.Add(Task.Run(() =>
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        ImageDBModel imageDBModel = new ImageDBModel()
                        {
                            Image    = ms.ToArray(),
                            Category = imageDTO.Category,
                            Type     = imageType
                        };
                        lock (this.dbContext)
                        {
                            this.dbContext.ImageDBModels.Add(imageDBModel);
                        }
                    }
                }));
            }
            //Wait for all images to insert into db
            await Task.WhenAll(fileTasks.ToArray());

            int changesCount;

            if ((changesCount = this.dbContext.SaveChanges()) > 0)
            {
                return(Ok(changesCount));
            }
            return(BadRequest(Models.Response.ErrorResponse("Failed to add new image")));
        }
        public IActionResult RemoveImageById(long id)
        {
            ImageDBModel imageDBModel = this.dbContext.ImageDBModels.FirstOrDefault(img => img.Id == id);

            if (imageDBModel == default)
            {
                return(NotFound());
            }
            else
            {
                this.dbContext.ImageDBModels.Remove(imageDBModel);
                this.dbContext.SaveChanges();
                return(Ok());
            }
        }
Exemple #4
0
        /// <summary>
        /// Upload image from file with longitude, lantitude and scale
        /// </summary>
        /// <param name="model">Model to upload</param>
        /// <returns>Task of (result, state, message)</returns>
        public async Task <(object, int, string)> UploadImageFromFile(UploadImageFileModel model, Guid UserId)
        {
            var filePath = _fileService.GetNextFilesPath(1, DirectoryType.Upload)[0];

            if (model.File.OpenReadStream().TryConvertToImage(out Image img))
            {
                img.Save(filePath, System.Drawing.Imaging.ImageFormat.Bmp);
                string       retUrl = filePath.Remove(0, filePath.LastIndexOf("\\images\\"));
                ImageDBModel image  = new ImageDBModel
                {
                    Cells     = null,
                    Expires   = DateTime.Now + TimeSpan.FromDays(1),
                    IsPreview = model.IsPreview,
                    Longitude = -1,
                    Latitude  = -1,
                    Scale     = -1,
                    URL       = retUrl
                };
                if (UserId == Guid.Empty)
                {
                    _applicationDBContext.Images.Add(image);
                }
                else
                {
                    _applicationDBContext.Users.Find(UserId).DownloadedImages.Add(image);
                }

                await _applicationDBContext.SaveChangesAsync();

                return(new
                {
                    resultImagePath = retUrl
                }, 200, "");
            }
            return("", 400, "File_Not_Image");
        }
Exemple #5
0
        /// <summary>
        /// Upload image from URL with longitude, lantitude and scale
        /// </summary>
        /// <param name="model">Model to upload</param>
        /// <returns>(result, state, message)</returns>
        public async Task <(object, int, string)> UploadImageFromURL(UploadImageURLModel model, Guid UserId)
        {
            if (!model.IsPreview)
            {
                ImageDBModel image = _applicationDBContext.Images.SingleOrDefault(img => img.URL == model.URL);
                if (image != null)
                {
                    image.Expires   = DateTime.Now + TimeSpan.FromDays(30);
                    image.Latitude  = model.Latitude;
                    image.IsPreview = false;
                    image.Longitude = model.Longitude;
                    image.Scale     = model.Scale;
                    await _applicationDBContext.SaveChangesAsync();

                    return(new
                    {
                        resultImagePath = model.URL
                    }, 200, "");
                }
                else
                {
                    //TODO: errors
                }
            }
            else
            {
                var filePath = _fileService.GetNextFilesPath(1, DirectoryType.Upload)[0];
                using (var client = new HttpClient())
                {
                    try
                    {
                        using (var result = await client.GetAsync(model.URL))
                        {
                            if (result.IsSuccessStatusCode)
                            {
                                if ((await result.Content.ReadAsStreamAsync()).TryConvertToImage(out Image img))
                                {
                                    img.Save(filePath, System.Drawing.Imaging.ImageFormat.Bmp);

                                    string       retUrl = filePath.Remove(0, filePath.LastIndexOf("\\images\\"));
                                    ImageDBModel image  = new ImageDBModel
                                    {
                                        Cells     = null,
                                        Expires   = DateTime.Now + TimeSpan.FromDays(1),
                                        IsPreview = model.IsPreview,
                                        Longitude = -1,
                                        Latitude  = -1,
                                        Scale     = -1,
                                        URL       = retUrl
                                    };
                                    if (UserId == Guid.Empty)
                                    {
                                        _applicationDBContext.Images.Add(image);
                                    }
                                    else
                                    {
                                        _applicationDBContext.Users.Find(UserId).DownloadedImages.Add(image);
                                    }

                                    await _applicationDBContext.SaveChangesAsync();

                                    return(new
                                    {
                                        resultImagePath = retUrl
                                    }, 200, "");
                                }
                                return("", 400, "File_Not_Image");
                            }
                        }
                    }
                    catch (HttpRequestException)
                    {
                        return("", 404, "Host_Not_found");
                    }
                }
            }
            return("", 404, "Unavailable_URL");
        }
Exemple #6
0
        /// <summary>
        /// Upload image from Google maps or Bing Maps with longitude, lantitude and scale
        /// </summary>
        /// <param name="model">Model to upload</param>
        /// <returns>(result, state, message)</returns>
        public async Task <(object, int, string)> UploadImageFromMaps(UploadImageMapModel model, Guid UserId)
        {
            var filePath = _fileService.GetNextFilesPath(1, DirectoryType.Upload)[0];
            var key      = "";
            var url      = "";

            switch (model.MapType)
            {
            case MapTypes.Bing:
                key = "AsxCWNx09JBu4SthLwqimpbExMR30Ho7iVzGaxCp6TsMzlDn9G7f3O6tZS40io7K";
                url = $@"https://dev.virtualearth.net/REST/v1/Imagery/Map/Aerial/{model.Latitude}," +
                      $@"{model.Longitude}/{model.Zoom}?mapSize={model.MapSizeX ?? 2000},{model.MapSizeY ?? 1500}&key={key}";
                break;

            case MapTypes.Google:
                key = "AIzaSyD1Gub16QiBvQ4olb_0HvFidiqQoPKsrkk";
                url = $@"https://maps.googleapis.com/maps/api/staticmap?center={model.Latitude}," +
                      $@"{model.Longitude}&zoom={model.Zoom}&size={model.MapSizeX ?? 640}x{model.MapSizeY ?? 640}&key={key}" +
                      "&maptype=satellite&scale=1&format=bmp";
                break;
            }
            using (var client = new HttpClient())
            {
                try
                {
                    using (var result = await client.GetAsync(url))
                    {
                        if (result.IsSuccessStatusCode)
                        {
                            //TODO: Handle error

                            if ((await result.Content.ReadAsStreamAsync()).TryConvertToImage(out Image img))
                            {
                                Bitmap bmp = (Bitmap)img;

                                if (model.MapType == MapTypes.Bing && (bmp.GetPixel(0, bmp.Height - 1).Name == "fff5f2ed" ||
                                                                       bmp.GetPixel(bmp.Width - 1, bmp.Height - 1).Name == "fff5f2ed") ||

                                    (model.MapType == MapTypes.Google && (bmp.GetPixel(0, bmp.Height - 1).Name == "ffe4e2de" ||
                                                                          bmp.GetPixel(bmp.Width - 1, bmp.Height - 1).Name == "ffe4e2de"))
                                    )
                                {
                                    return("", 400, "Image_So_Zommed");
                                }
                                img.Save(filePath, System.Drawing.Imaging.ImageFormat.Bmp);
                                string       retUrl = filePath.Remove(0, filePath.LastIndexOf("\\images\\"));
                                ImageDBModel image  = new ImageDBModel
                                {
                                    Cells   = null,
                                    Expires = model.IsPreview ? DateTime.Now + TimeSpan.FromDays(1) :
                                              DateTime.Now + TimeSpan.FromDays(30),
                                    IsPreview = model.IsPreview,
                                    Longitude = model.Longitude,
                                    Latitude  = model.Latitude,
                                    Scale     = -1,
                                    URL       = retUrl
                                };
                                if (UserId == Guid.Empty)
                                {
                                    _applicationDBContext.Images.Add(image);
                                }
                                else
                                {
                                    _applicationDBContext.Users.Find(UserId).DownloadedImages.Add(image);
                                }

                                await _applicationDBContext.SaveChangesAsync();

                                return(new
                                {
                                    resultImagePath = retUrl
                                }, 200, "");
                            }
                            return("", 400, "File_Not_Image");
                        }
                    }
                }
                catch (HttpRequestException)
                {
                    return("", 404, "Host_Not_found");
                }
            }
            return("", 400, "Unavailable_URL");
        }