Exemple #1
0
        private async Task ExecuteCameraCommand()
        {
            MediaFile file = await CrossMedia.Current.TakePhotoAsync(
                new StoreCameraMediaOptions { PhotoSize = PhotoSize.Small });

            if (file == null)
            {
                return;
            }

            byte[] imageAsBytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                file.Dispose();
                imageAsBytes = memoryStream.ToArray();
            }

            if (imageAsBytes.Length > 0)
            {
                IImageResizer resizer = DependencyService.Get <IImageResizer>();
                imageAsBytes = resizer.ResizeImage(imageAsBytes, 1080, 1080);

                string base64String = Convert.ToBase64String(imageAsBytes);
                Debug.WriteLine(base64String);

                ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
                Images.Add(new ImageModel {
                    Source = imageSource, OrgImage = imageAsBytes
                });
            }
        }
        public void ReturnResizeResult()
        {
            var resizeRequest = new ResizeRequest(LargeImage, 100, 100);

            var sw = new Stopwatch();

            sw.Start();

            using (var resizeResult = _imageResizer.ResizeImage(resizeRequest))
            {
                sw.Stop();

                _output.WriteLine($"Took:{sw.Elapsed}");

                resizeResult.ShouldBeOfType <ResizeResult>();
                resizeResult.ImageData.Length.ShouldBeGreaterThanOrEqualTo(1);
            }
        }
Exemple #3
0
        public async Task <IActionResult> GetImage(string name,
                                                   [FromQuery] int?width = null, [FromQuery] int?height = null)
        {
            try
            {
                var stream = await _imageService.GetImageByName(name);

                if (HttpContext.Request.Query.Count > 0)
                {
                    stream = await imageResizer.ResizeImage(stream, width, height);
                }

                return(File(stream, "image/jpg"));
            }
            catch (FileNotFoundException)
            {
                return(NotFound());
            }
        }
Exemple #4
0
        private void AddTheImages(int imageIssueId)
        {
            var imageData = App.Client.GetImage(imageIssueId);

            byte[] imageAsBytes = imageData.Item1;

            if (imageAsBytes.Length > 0)
            {
                IImageResizer resizer = DependencyService.Get <IImageResizer>();
                imageAsBytes = resizer.ResizeImage(imageAsBytes, 1080, 1080);

                ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
                Images.Add(new ImageModel {
                    Source = imageSource, OrgImage = imageAsBytes
                });

                // Debug to check if images are valid when being download. They are
                string base64String = Convert.ToBase64String(imageAsBytes);
                Debug.WriteLine(base64String);
            }
        }
        public async Task <UploadResult> ProcessFile(
            IFormFile formFile,
            ImageProcessingOptions options,
            bool?resizeImages,
            int?maxWidth,
            int?maxHeight,
            string requestedVirtualPath = "",
            string newFileName          = "",
            bool allowRootPath          = true,
            bool createThumbnail        = false,
            bool?keepOriginal           = null
            )
        {
            await EnsureProjectSettings().ConfigureAwait(false);

            string currentFsPath      = _rootPath.RootFileSystemPath;
            string currentVirtualPath = _rootPath.RootVirtualPath;

            string[] virtualSegments = options.ImageDefaultVirtualSubPath.Split('/');
            bool     doResize        = resizeImages ?? options.AutoResize;

            if ((!string.IsNullOrEmpty(requestedVirtualPath)) && (requestedVirtualPath.StartsWith(_rootPath.RootVirtualPath)))
            {
                var virtualSubPath = requestedVirtualPath.Substring(_rootPath.RootVirtualPath.Length);
                var segments       = virtualSubPath.Split('/');
                if (segments.Length > 0)
                {
                    var requestedFsPath = Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments));
                    if (!Directory.Exists(requestedFsPath))
                    {
                        //_log.LogError("directory not found for currentPath " + requestedFsPath);
                        // user has file system permission and could manually create the needed folder so auto ensure
                        // since it is a sub path of the root
                        EnsureSubFolders(_rootPath.RootFileSystemPath, segments);
                    }

                    currentVirtualPath = requestedVirtualPath;
                    virtualSegments    = segments;
                    currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                }
            }
            else
            {
                // ensure the folders if no currentDir provided,
                // if it is provided it must be an existing path
                // options.ImageDefaultVirtualSubPath might not exist on first upload so need to ensure it
                if (!allowRootPath)
                {
                    currentVirtualPath = currentVirtualPath + options.ImageDefaultVirtualSubPath;
                    currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                    EnsureSubFolders(_rootPath.RootFileSystemPath, virtualSegments);
                }
            }
            string newName;

            if (!string.IsNullOrEmpty(newFileName))
            {
                newName = _nameRules.GetCleanFileName(newFileName);
            }
            else
            {
                newName = _nameRules.GetCleanFileName(Path.GetFileName(formFile.FileName));
            }

            var newUrl = currentVirtualPath + "/" + newName;
            var fsPath = Path.Combine(currentFsPath, newName);

            var ext         = Path.GetExtension(newName);
            var webSizeName = Path.GetFileNameWithoutExtension(newName) + "-ws" + ext;

            string webUrl = currentVirtualPath + "/" + webSizeName;

            var    thumbSizeName = Path.GetFileNameWithoutExtension(newName) + "-thumb" + ext;
            string thumbUrl      = currentVirtualPath + "/" + thumbSizeName;

            var didResize      = false;
            var didCreateThumb = false;

            try
            {
                using (var stream = new FileStream(fsPath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
                var mimeType = GetMimeType(ext);

                if ((doResize) && IsWebImageFile(ext))
                {
                    int resizeWidth  = GetMaxWidth(maxWidth, options);
                    int resizeHeight = GetMaxWidth(maxHeight, options);

                    didResize = _imageResizer.ResizeImage(
                        fsPath,
                        currentFsPath,
                        webSizeName,
                        mimeType,
                        resizeWidth,
                        resizeHeight,
                        options.AllowEnlargement,
                        options.ResizeQuality
                        );
                }

                if (createThumbnail)
                {
                    didCreateThumb = _imageResizer.ResizeImage(
                        fsPath,
                        currentFsPath,
                        thumbSizeName,
                        mimeType,
                        options.ThumbnailImageMaxWidth,
                        options.ThumbnailImageMaxHeight,
                        false,
                        options.ResizeQuality
                        );
                }
                if (didResize)
                {
                    if (keepOriginal.HasValue)
                    {
                        if (keepOriginal.Value == false)
                        {
                            File.Delete(fsPath);
                            newUrl = string.Empty;
                        }
                    }
                    else if (!options.KeepOriginalImages) // use default if not explcitely passed
                    {
                        File.Delete(fsPath);
                        newUrl = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"{ex.Message}:{ex.StackTrace}");

                return(new UploadResult
                {
                    ErrorMessage = _sr["There was an error logged during file processing"]
                });
            }

            return(new UploadResult
            {
                OriginalUrl = newUrl,
                ResizedUrl = didResize ? webUrl : string.Empty,
                ThumbUrl = didCreateThumb ? thumbUrl : string.Empty,
                Name = newName,
                Length = formFile.Length,
                Type = formFile.ContentType
            });
        }
        public async Task <UploadResult> ProcessFile(
            IFormFile formFile,
            ImageProcessingOptions options,
            bool?resizeImages,
            int?maxWidth,
            int?maxHeight,
            string requestedVirtualPath = "",
            string newFileName          = "",
            bool allowRootPath          = true
            )
        {
            await EnsureProjectSettings().ConfigureAwait(false);

            string currentFsPath      = rootPath.RootFileSystemPath;
            string currentVirtualPath = rootPath.RootVirtualPath;

            string[] virtualSegments = options.ImageDefaultVirtualSubPath.Split('/');
            bool     doResize        = resizeImages.HasValue ? resizeImages.Value : options.AutoResize;

            if ((!string.IsNullOrEmpty(requestedVirtualPath)) && (requestedVirtualPath.StartsWith(rootPath.RootVirtualPath)))
            {
                var virtualSubPath = requestedVirtualPath.Substring(rootPath.RootVirtualPath.Length);
                var segments       = virtualSubPath.Split('/');
                if (segments.Length > 0)
                {
                    var requestedFsPath = Path.Combine(rootPath.RootFileSystemPath, Path.Combine(segments));
                    if (!Directory.Exists(requestedFsPath))
                    {
                        log.LogError("directory not found for currentPath " + requestedFsPath);
                    }
                    else
                    {
                        currentVirtualPath = requestedVirtualPath;
                        virtualSegments    = segments;
                        currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                    }
                }
            }
            else
            {
                // only ensure the folders if no currentDir provided,
                // if it is provided it must be an existing path
                // options.ImageDefaultVirtualSubPath might not exist on first upload so need to ensure it
                if (!allowRootPath)
                {
                    currentVirtualPath = currentVirtualPath + options.ImageDefaultVirtualSubPath;
                    currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                    EnsureSubFolders(rootPath.RootFileSystemPath, virtualSegments);
                }
            }
            string newName;

            if (!string.IsNullOrEmpty(newFileName))
            {
                newName = nameRules.GetCleanFileName(newFileName);
            }
            else
            {
                newName = nameRules.GetCleanFileName(Path.GetFileName(formFile.FileName));
            }

            var newUrl = currentVirtualPath + "/" + newName;
            var fsPath = Path.Combine(currentFsPath, newName);

            var    ext         = Path.GetExtension(newName);
            var    webSizeName = Path.GetFileNameWithoutExtension(newName) + "-ws" + ext;
            var    webFsPath   = Path.Combine(currentFsPath, webSizeName);
            string webUrl      = string.Empty;
            var    didResize   = false;

            try
            {
                using (var stream = new FileStream(fsPath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }

                if ((doResize) && IsWebImageFile(ext))
                {
                    var mimeType = GetMimeType(ext);
                    webUrl = currentVirtualPath + "/" + webSizeName;
                    int resizeWidth  = GetMaxWidth(maxWidth, options);
                    int resizeHeight = GetMaxWidth(maxHeight, options);

                    didResize = imageResizer.ResizeImage(
                        fsPath,
                        currentFsPath,
                        webSizeName,
                        mimeType,
                        resizeWidth,
                        resizeHeight,
                        options.AllowEnlargement
                        );
                }

                return(new UploadResult
                {
                    OriginalUrl = newUrl,
                    ResizedUrl = didResize? webUrl : string.Empty,
                    Name = newName,
                    Length = formFile.Length,
                    Type = formFile.ContentType
                });
            }
            catch (Exception ex)
            {
                log.LogError(MediaLoggingEvents.FILE_PROCCESSING, ex, ex.StackTrace);

                return(new UploadResult
                {
                    ErrorMessage = sr["There was an error logged during file processing"]
                });
            }
        }