示例#1
0
        void showRow(ImagesRow row, int top, int left, int width, double vgap, ImageAction action, ref int i)
        {
            int    rowWidth  = row.Width;
            int    rowHeight = row.Height;
            double gap       = ((double)(width - rowWidth) / (double)row.Count);

            for (int cell = 0; cell < row.Count; ++cell)
            {
                if (mPictures.Count <= i)
                {
                    AddPictureBox();
                }

                IRowItem item = row[cell];
                if (item.GetItemType() == RowType.Image)
                {
                    StackableImage image = item as StackableImage;
                    mPictures[i].mPictureBox.Left   = left;
                    mPictures[i].mPictureBox.Top    = top;
                    mPictures[i].mPictureBox.Height = (int)Math.Round(rowHeight + vgap);
                    mPictures[i].mPictureBox.Width  = (int)Math.Round(image.Width + gap);
                    left = mPictures[i].mPictureBox.Left + mPictures[i].mPictureBox.Width;

                    showNextImage(mPictures[i], action, image);
                    mPictures[i].mPictureBox.Show();
                    ++i;
                }
                else if (item.GetItemType() == RowType.Rows)
                {
                    showRows(item as ImagesRows, top, left, row.Height, (int)(item.Width + gap), action, ref i);
                    left += (int)(item.Width + gap);
                }
            }
        }
示例#2
0
        public void updateImages(ImageAction action)
        {
            ImagesLayout oldLayout = mLayout;

            mLayout = mScreenComposer.GetNextLayout();
            if (mLayout != null)
            {
                ImagesRows rows = mLayout.Rows;
                int        i    = 0;
                showRows(rows, 0, 0, Size.Height, Size.Width, action, ref i);
                for (int picture = i; picture < mPictures.Count; ++picture)
                {
                    mPictures[picture].mPictureBox.Hide();
                    showNextImage(mPictures[picture], action, null);
                }
            }
            else
            {
                for (int picture = 0; picture < mPictures.Count; ++picture)
                {
                    mPictures[picture].mPictureBox.Hide();
                    showNextImage(mPictures[picture], action, null);
                }
            }
            if (oldLayout != null)
            {
                oldLayout.Dispose();
            }
        }
示例#3
0
        public ActionResult GetImage(ImageAction imageaction)
        {
            WebImage image = new WebImage(Server.MapPath("~/images/twmvclogo.png"));


            switch (imageaction)
            {
            case ImageAction.Resize:
                image = image.Resize(100, 100);
                break;

            case ImageAction.Flip:
                image = image.FlipVertical();
                break;

            case ImageAction.Watermark:
                image = image.AddTextWatermark("TW MVC");
                break;

            case ImageAction.Crop:
                image = image.Crop(50, 50, 50, 50);
                break;

            default:
                throw new ArgumentException("尚未實作");
            }

            return(File(image.GetBytes(), "image/png"));
        }
示例#4
0
        public PartialViewResult RateImage(IFormCollection collection, ImageAction action)
        {
            var signedInUserId = Convert.ToInt64(HttpContext.Session.GetString("StudioLoggedInUserId"));

            action.Action     = "Rating";
            action.ActionDate = DateTime.Now;
            action.AppUserId  = signedInUserId;
            action.OwnerId    = signedInUserId;
            action.ImageId    = Convert.ToInt64(collection["ImageId"]);
            action.Rating     = Convert.ToInt64(collection["rating"]);
            action.ClientId   = new AppConfig().ClientId;
            if (_databaseConnection.ImageActions
                .Where(n => n.ImageId == action.ImageId && n.AppUserId == action.AppUserId).ToList().Count <= 0)
            {
                _databaseConnection.Add(action);
                _databaseConnection.SaveChanges();
            }
            var image        = _databaseConnection.Images.SingleOrDefault(n => n.ImageId == action.ImageId);
            var appTransport = new AppTransport
            {
                AppUsers     = _users,
                Images       = _databaseConnection.Images.ToList(),
                ImageActions = _databaseConnection.ImageActions.ToList(),
                Image        = image,
                AppUser      = _users.SingleOrDefault(n => n.AppUserId == signedInUserId)
            };

            return(PartialView("Partials/_PartialRating", appTransport));
        }
        protected async void OnOkCommand()
        {
            try
            {
                await _SemaphoreSlimOnOkCommand.WaitAsync();

                UpdateOptionSettings();
                _loggerService?.LogEvent(nameof(OnOkCommand));
                ImageAction Action      = OverwriteFiles ? ImageAction.Save : ImageAction.SaveAs;
                bool        successfull = await ResizeImages(Action);

                if (successfull && _localSettings.Settings.ClearImageListAfterSuccess && ImageFiles?.Count != 0)
                {
                    CancelCommand?.Execute(ImageFiles);
                }
                //if the app was started from command line exit the app after resize
                if (AppStartType.CommandLine.Equals(_appStartType))
                {
                    _applicationService.Exit();
                }
            }
            catch (Exception e)
            {
                _loggerService?.LogException(nameof(OnOkCommand), e);
            }
            finally
            {
                _SemaphoreSlimOnOkCommand.Release();
            }
        }
示例#6
0
 private void RestoreProperties(ImageAction action, JObject actionData)
 {
     foreach (var prop in this.GetImportExportProperties(action))
     {
         if (actionData.ContainsKey(prop.Name))
         {
             prop.SetValue(action, Convert.ChangeType(actionData[prop.Name], prop.PropertyType));
         }
     }
 }
示例#7
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string ids = WS.RequestString("id");

            ImageAction.DeleteImageAlbum(string.Format("id in ({0})", ids));

            if (cls > 0)
            {
                CreatePage.CreateListPage(ClassView.GetModelByID(cls.ToS()), 1);
            }
            CreatePage.GreateIndexPage();
            Js.AlertAndChangUrl("删除成功!", url);
        }
示例#8
0
        void showRows(ImagesRows rows, int top, int left, int height, int width, ImageAction action, ref int i)
        {
            if (rows.RowCount == 0)
            {
                return;
            }
            double vgap = ((double)(height - rows.Height) / (double)rows.RowCount);

            for (int row = 0; row < rows.RowCount; ++row)
            {
                IRowItem item = rows[row];
                showRow(item as ImagesRow, top, left, width, vgap, action, ref i);
                top += (int)Math.Round(item.Height + vgap);
            }
        }
示例#9
0
        private double GetPriceFromResult(ImageAction image)
        {
            var price = 0.0;

            if (image.InsightsMetadata != null && image.InsightsMetadata.AggregateOffer != null)
            {
                price = image.InsightsMetadata.AggregateOffer.Offers.First().Price;
            }
            else
            {
                price = new Random().Next(15, 50) + 0.99;
            }

            return(price);
        }
        public void AddListener(Image target, ImageAction imageAction)
        {
            ImageActionParmes findparmes = imageListaction.Find((ImageActionParmes parms) => { return(parms.image == target); });

            if (findparmes.image != null)
            {
                imageListaction.Remove(findparmes);
            }
            findparmes.image  = target;
            findparmes.action = imageAction;
            imageListaction.Add(new ImageActionParmes()
            {
                action = imageAction, image = target
            });
        }
示例#11
0
        public Tuple <string, int, int> GenerateImagePreview(string localPath)
        {
            string ext = Path.GetExtension(localPath);

            newLocalPath = string.Empty;
            newLocalPath = localPath.Replace(ext, "_p" + ext);

            //压缩图片
            ImageAction.ThumbnailResult ret = ImageAction.ThumbnailImage(localPath, newLocalPath);
            if (ret.Success)
            {
                return(new Tuple <string, int, int>(accessDir + Path.GetFileName(newLocalPath), ret.ImageWidth, ret.ImageHeight));
            }

            return(null);
        }
示例#12
0
        public async Task <JsonResult> SaveImageAction([FromBody] ImageAction action)
        {
            var actionExist =
                _databaseConnection.ImageActions.Where(
                    n => n.AppUserId == action.AppUserId && n.ImageId == action.ImageId).ToList();

            if (actionExist.Count <= 0)
            {
                _databaseConnection.Add(action);
                _databaseConnection.SaveChanges();
                var image = _databaseConnection.Images.SingleOrDefault(n => n.ImageId == action.ImageId);
                if (image != null)
                {
                    var notification = new PushNotification
                    {
                        AppUserId        = action.OwnerId,
                        CreatedBy        = action.AppUserId,
                        LastModifiedBy   = action.AppUserId,
                        DateLastModified = DateTime.Now,
                        DateCreated      = DateTime.Now,
                        Category         = SystemNotificationCategory.Comment.ToString(),
                        Read             = false,
                        ControllerId     = image.ImageId,
                        ClientId         = 4
                    };

                    var singleOrDefault = new AppUserFactory()
                                          .GetAllUsers(new AppConfig().FetchUsersUrl).Result
                                          .SingleOrDefault(n => n.AppUserId == image.AppUserId);
                    if (singleOrDefault != null)
                    {
                        notification.Message = singleOrDefault.Name +
                                               " Rated your Image";
                    }
                    await new AppUserFactory().SavePushNotification(new AppConfig().SavePushNotifications, notification);
                }
            }
            return(Json(action));
        }
示例#13
0
        public void ImageActionSetCorrectly([EnumValues] ImageAction imageAction)
        {
            IndexingParameters parameters = new IndexingParameters().SetImageAction(imageAction);

            AssertHasConfigItem(parameters, "imageAction", imageAction.ToString());
        }
示例#14
0
        public string PerformImageAction(ImageAction action, string message)
        {
            string JsonReturn = "";

            if (txtServer.InvokeRequired)
            {
                Invoke(imageFormActionDelegate, action, message);
                return JsonReturn;
            }

            else
            {
                if (action == ImageAction.InitialiseImages)
                {
                    if (imageDisplay != null)
                    {
                        imageDisplay.Dispose();
                        imageDisplay2.Dispose();
                        imageDisplay = null;
                        imageDisplay2 = null;
                    }

                    imageDisplay = new ImageDisplay(1, message); //expecting direction to reset to 0 if new one opened
                    imageDisplay2 = new ImageDisplay(2, message);
                    if (videoDisplay != null)
                    {
                        videoDisplay.Dispose();
                        videoDisplay2.Dispose();
                        videoDisplay = null;
                        videoDisplay2 = null;
                    }

                    imageDisplay.Width = screens * resolutionWidth;
                    imageDisplay2.Width = screens * resolutionWidth;
                    imageDisplay.Height = resolutionHight;
                    imageDisplay2.Height = resolutionHight;
                    imageDisplay.StartPosition = FormStartPosition.Manual;
                    imageDisplay.Location = new Point(0, 0);
                    imageDisplay2.StartPosition = FormStartPosition.Manual;
                    imageDisplay2.Location = new Point(0, 0);
                    imageDisplay.Show();
                    imageDisplay2.Show();
                    JsonReturn = "{\"messageType\":\"ImageViewer\",\"messageBody\":\"Image Initialised\"}";

                    return JsonReturn;

                }

                else
                {
                    JsonReturn = "image action failed";
                    return JsonReturn;
                }

            }
        }
示例#15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpPostedFile file = Request.Files[0];

            ImageAction.UpLoadImage(file, WS.RequestInt("id"));
        }
示例#16
0
 private IEnumerable <PropertyInfo> GetImportExportProperties(ImageAction action)
 {
     return(action.GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)
            .Where(prop => prop.GetCustomAttribute <ImportExportAttribute>() != null));
 }
示例#17
0
 private Dictionary <string, object> GetActionProperties(ImageAction action)
 {
     return(this.GetImportExportProperties(action)
            .Select(p => new { p.Name, Value = p.GetValue(action) })
            .ToDictionary(i => i.Name, i => i.Value));
 }
示例#18
0
        void showNextImage(PictureControlDesc picture, ImageAction action, StackableImage next)
        {
            System.Drawing.Image img = next == null ? null : next.Image;
            if (picture.mPictureBox.Image != null)
            {
                picture.mPictureBox.Image.Dispose();
            }
            if (img == null)
            {
                picture.mPictureBox.Image = null;
            }
            else
            {
                try
                {
                    //TODO: optimize
                    picture.mPictureBox.Image = (System.Drawing.Image)img.Clone();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("This is the exception I'm searched for! " + ex.ToString(),
                                    "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (picture.mImageDescriptor != null)
            {
                switch (action)
                {
                case ImageAction.Reuse:
                    mImagesLoader.Return(picture.mImageDescriptor.Path);
                    break;

                case ImageAction.Delete:
                    picture.mImageDescriptor.Dispose();
                    try
                    {
                        if (string.IsNullOrEmpty(mOptions.MoveDeletedPath))
                        {
                            System.IO.File.Delete(picture.mImageDescriptor.Path);
                        }
                        else
                        {
                            moveFile(picture.mImageDescriptor.Path, mOptions.MoveDeletedPath);
                        }
                    }
                    catch (IOException ex)
                    {
                        System.IO.File.SetAttributes(picture.mImageDescriptor.Path, FileAttributes.Normal);
                        // do nothing
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        if (System.IO.File.GetAttributes(picture.mImageDescriptor.Path).HasFlag(System.IO.FileAttributes.ReadOnly))
                        {
                            System.IO.File.SetAttributes(picture.mImageDescriptor.Path, FileAttributes.Normal);
                            System.IO.File.Delete(picture.mImageDescriptor.Path);
                        }
                    }
                    break;

                case ImageAction.Move:
                {
                    picture.mImageDescriptor.Dispose();
                    string movePath = mOptions.MovePath;
                    moveFile(picture.mImageDescriptor.Path, movePath);
                }
                break;

                case ImageAction.Skip:
                    picture.mImageDescriptor.Dispose();
                    break;
                }
            }
            picture.mImageDescriptor = next;
        }
示例#19
0
 private bool FilterImageBySize(ImageAction imageAction)
 {
     return(imageAction.Width == 400 && imageAction.Name.ToLower().Contains("watch"));
 }
示例#20
0
        public async Task <ResxResult> SaveStream()
        {
            provider = new MultipartFormDataMemoryStreamProvider();
            await request.Content.ReadAsMultipartAsync(provider);

            if (provider == null ||
                provider.FileData == null ||
                provider.FileData.Count <= 0)
            {
                throw new Exception("上传资源不能为空");
            }

            var fileCount = provider.FileData.Count();

            if (fileCount > ResxConfigManager.RESX_MAX_COUNT)
            {
                throw new Exception("上传资源数量超过大小");
            }

            var count = provider.FileData.Where(f => !this.resxModel.ResxTypes.Contains(Path.GetExtension(f.Headers.ContentDisposition.FileName.Replace("\"", "")))).Count();

            if (count > 0)
            {
                throw new Exception("上传包含未知资源类型");
            }

            List <Stream> streamList  = new List <Stream>();
            List <string> streamNames = new List <string>();

            foreach (MultipartFileData file in provider.FileData)
            {
                Stream stream = ((MultipartFileDataStream)file).Stream;
                if (stream.Length > this.resxModel.ResxSize && this.resxModel.ResxSize > 0)
                {
                    throw new Exception("上传资源超过大小");
                }
                else
                {
                    streamList.Add(stream);
                    streamNames.Add(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                }
            }

            int        i      = 0;
            ResxResult result = new ResxResult()
            {
                Success = false
            };

            foreach (Stream stream in streamList)
            {
                string localPath = Path.Combine(rootDir, streamNames[i]);
                using (StreamWriter sw = new StreamWriter(localPath))
                {
                    stream.CopyTo(sw.BaseStream);
                    sw.Flush();

                    string orgUrl = Path.Combine(accessDir, streamNames[i]);

                    result.Success      = true;
                    result.OriginalUrl  = orgUrl;
                    result.OriginalSize = sw.BaseStream.Length;

                    //检测是否要生成预览图片
                    if (this.resxModel.IsPreview() && sw.BaseStream.Length > ResxConfigManager.PREVIEW_IMAGE_SIZE)
                    {
                        //log.WriterLog("检测是否要生成预览图片sw.BaseStream.Length=" + sw.BaseStream.Length + "   PREVIEW_IMAGE_SIZE=" + ResxConfigManager.PREVIEW_IMAGE_SIZE);
                        string ext          = Path.GetExtension(streamNames[i]);
                        string newLocalPath = localPath.Replace(ext, "_p" + ext);

                        //压缩图片
                        ImageAction.ThumbnailResult ret = ImageAction.ThumbnailImage(localPath, newLocalPath);
                        if (ret.Success)
                        {
                            result.PreviewUrl = orgUrl.Replace(ext, "_p" + ext);
                            //result.PreviewSize = ;
                            result.Width  = ret.ImageWidth;
                            result.Height = ret.ImageHeight;
                            //log.WriterLog("压缩成功:" + result.PreviewUrl);
                        }
                        else
                        {
                            result.PreviewUrl  = orgUrl;
                            result.PreviewSize = sw.BaseStream.Length;
                            //log.WriterLog("压缩失败:" + result.PreviewUrl);
                        }
                    }

                    //检测是否是语音文件
                    //.....

                    //检测是否是视频文件
                    //.....
                }
                i++;
            }

            return(result);
        }
示例#21
0
        public List <ResxResult> SaveFile()
        {
            this.LoadUpfiles();

            List <ResxResult> resxResults = new List <ResxResult>();
            ResxResult        resx        = null;

            foreach (var file in this.files)
            {
                string newFileName = GetNewFileName(Path.GetExtension(file.FileName).ToLower());
                string localPath   = Path.Combine(rootDir, newFileName);
                string orgUrl      = Path.Combine(accessDir, newFileName);

                //保存图片
                try
                {
                    file.SaveAs(localPath);
                    resx = new ResxResult()
                    {
                        Success      = true,
                        OriginalUrl  = orgUrl,
                        OriginalSize = file.InputStream.Length,
                        //PreviewUrl = orgUrl.Replace(ext, "_p" + ext),
                        //PreviewSize = ret.NewImageSize,
                        //Width = ret.ImageWidth,
                        //Height = ret.ImageHeight
                    };
                }
                catch (Exception)
                {
                    resx = new ResxResult()
                    {
                        Success = false
                    };
                }

                if (resx.Success)
                {
                    //检测是否要生成预览图片
                    try
                    {
                        if (this.resxModel.IsPreview() && file.InputStream.Length > ResxConfigManager.PREVIEW_IMAGE_SIZE)
                        {
                            var info = GenerateImagePreview(localPath);
                            if (info != null)
                            {
                                resx.PreviewUrl  = info.Item1;
                                resx.Width       = info.Item2;
                                resx.Height      = info.Item3;
                                resx.PreviewSize = GetResxLength();
                            }
                        }
                        else if (this.resxModel.IsImage())
                        {
                            var info = ImageAction.GetSize(localPath);
                            if (info != null)
                            {
                                resx.Width  = info.Item1;
                                resx.Height = info.Item2;
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                //检测是否是语音文件
                //.....

                //检测是否是视频文件
                //.....

                resxResults.Add(resx);
            }
            return(resxResults);
        }
示例#22
0
 public ImageController()
 {
     _imageAction = new ImageAction("/home/pi/Photos");
 }
示例#23
0
        public bool ExtendedHitTest(object sender, Point point, bool click)
        {
            if (m_resizedImage == null)
            {
                return(false);
            }

            if (m_dragAction != ImageAction.None)
            {
                if (OnAction != null)
                {
                    OnAction(this, m_dragAction, point, click);
                }

                if (click)
                {
                    m_dragAction = ImageAction.None;
                }

                return(true);
            }

            ImageAction action = ImageAction.None;

            Cursor cursor = Cursors.Default;

            if (Selected)
            {
                Rectangle border = new Rectangle((int)(m_fpoints[0].X + m_realBounds.X + m_tempOffset.X), (int)(m_fpoints[0].Y + m_realBounds.Y + m_tempOffset.Y), m_realBounds.Width, m_realBounds.Height);

                if (Scalable)
                {
                    Rectangle NW = new Rectangle(border.X - HANDLE_SIZE / 2, border.Y - HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE);

                    if (NW.Contains(point))
                    {
                        cursor = Cursors.SizeNWSE;
                        action = ImageAction.Scale;
                    }

                    Rectangle NE = new Rectangle(border.X + border.Width - HANDLE_SIZE - 1 + HANDLE_SIZE / 2, border.Y - HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE);

                    if (NE.Contains(point))
                    {
                        cursor = Cursors.SizeNESW;
                        action = ImageAction.Scale;
                    }

                    Rectangle SW = new Rectangle(border.X - HANDLE_SIZE / 2, border.Y + border.Height - HANDLE_SIZE - 1 + HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE);
                    if (SW.Contains(point))
                    {
                        cursor = Cursors.SizeNESW;
                        action = ImageAction.Scale;
                    }

                    Rectangle SE = new Rectangle(border.X + border.Width - HANDLE_SIZE - 1 + HANDLE_SIZE / 2, border.Y + border.Height - HANDLE_SIZE - 1 + HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE);

                    if (SE.Contains(point))
                    {
                        cursor = Cursors.SizeNWSE;
                        action = ImageAction.Scale;
                    }
                }

                if (Movable)
                {
                    Rectangle center = new Rectangle(border.X + border.Width / 2 - MOVE_HANDLE_SIZE / 2, border.Y + border.Height / 2 - MOVE_HANDLE_SIZE / 2, MOVE_HANDLE_SIZE, MOVE_HANDLE_SIZE);

                    if (center.Contains(point))
                    {
                        cursor = Cursors.SizeAll;
                        action = ImageAction.Move;
                    }
                }

                if (Rotatable)
                {
                    Rectangle pivot = new Rectangle((int)(m_fpoints[0].X + m_resizedImage.Width / 2 - ROTATE_HANDLE_SIZE / 2 + m_tempOffset.X - ROTATE_HANDLE_OFFSET), (int)(m_fpoints[0].Y + m_resizedImage.Height / 2 - ROTATE_HANDLE_SIZE / 2 + m_tempOffset.Y - ROTATE_HANDLE_OFFSET), ROTATE_HANDLE_SIZE, ROTATE_HANDLE_SIZE);

                    if (pivot.Contains(point))
                    {
                        cursor = Cursors.PanEast;
                        action = ImageAction.Rotate;
                    }
                }
            }

            //if(cursor != Cursors.Default)
            //((Control)sender).Cursor = cursor;

            if (action == ImageAction.None)
            {
                return(false);
            }

            if (click)
            {
                if (OnAction != null)
                {
                    OnAction(this, action, point, false);
                }
                m_dragAction = action;
            }

            return(true);
        }
        /// <summary>
        /// Starts resizing the image operation
        /// </summary>
        /// <param name="action">Determine whether the image files should be saved as, or updated or resize image is used from sharing</param>
        /// <param name="processedImageAction">Action method which retrievs the resized image. Can be used for sharing.</param>
        /// <returns>Task which indicates if the current resize operation was successfull</returns>
        public async Task <bool> ResizeImages(ImageAction action, Action <ImageFile, String> processedImageAction = null)
        {
            IProgressBarDialogService progressBarDialog = !IsShareTarget?_progressBarDialogService.ProgressBarDialogFactory() : null;

            try
            {
                Resizing = true;
                //if no file is selected open file picker
                if (ImageFiles == null || ImageFiles.Count == 0)
                {
                    await OpenFilePicker();
                }

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                progressBarDialog?.StartAsync(ImageFiles.Count);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                String    suggestedFileName   = String.Empty;
                String    targetStorageFolder = Settings.DefaultSaveAsTargetFolder;
                Exception lastException       = null;
                if (ImageFiles != null)
                {
                    foreach (ImageFile currentImage in ImageFiles)
                    {
                        try
                        {
                            SelectedFile      = currentImage;
                            suggestedFileName = _imageFileService.GenerateResizedFileName(currentImage, currentImage.NewWidth, currentImage.NewHeight);
                            if (progressBarDialog != null)
                            {
                                progressBarDialog.CurrentItem = suggestedFileName;
                            }
                            //if the stream is disposed CanSeek and CanRead is false
                            if (currentImage.Stream == null || !currentImage.Stream.CanSeek && !currentImage.Stream.CanRead)
                            {
                                var imageFile = (await _imageFileService.LoadImageFileAsync(currentImage.Path));
                                if (imageFile?.Stream != null)
                                {
                                    currentImage.Stream = imageFile.Stream;
                                }
                                else
                                {
                                    _loggerService.LogEvent("Could not load stream.", new Dictionary <string, string>()
                                    {
                                        { nameof(currentImage.Path), currentImage.Path }
                                    });
                                    continue;
                                }
                            }
                            TaskCompletionSource <MemoryStream> taskMemoryStreamCompletionSource = new TaskCompletionSource <MemoryStream>();
                            if (!IsShareTarget)
                            {
                                //do the resizing in a seperate thread using Task.Run
                                try
                                {
                                    var ms = await Task.Run(() => _resizeService.ResizeAsync(currentImage.Stream, currentImage.NewWidth, currentImage.NewHeight, suggestedFileName, _localSettings.Settings.ImageQuality));

                                    taskMemoryStreamCompletionSource.SetResult(ms);
                                }
                                catch (Exception e)
                                {
                                    taskMemoryStreamCompletionSource.SetException(e);
                                }
                            }
                            else
                            {
                                //do the resizing on the main thread in share target to avoid issues see #53
                                var ms = await _resizeService.ResizeAsync(currentImage.Stream, currentImage.NewWidth, currentImage.NewHeight, suggestedFileName, _localSettings.Settings.ImageQuality);

                                taskMemoryStreamCompletionSource.SetResult(ms);
                            }
                            using (MemoryStream resizedImageFileStream = await taskMemoryStreamCompletionSource.Task)
                            {
                                //log image size
                                _loggerService?.LogEvent(nameof(IResizeService.ResizeAsync), new Dictionary <String, String>()
                                {
                                    { $"{nameof(ImageFile)}{nameof(Width)}", $"{currentImage?.Width}" },
                                    { $"{nameof(ImageFile)}{nameof(Height)}", $"{currentImage?.Height}" },
                                    { nameof(Width), $"{currentImage?.NewHeight }" },
                                    { nameof(Height), $"{currentImage?.NewHeight}" },
                                    { nameof(ImageAction), $"{action}" }
                                });
                                //overwrite current ImageStoreage
                                if (action.Equals(ImageAction.Save))
                                {
                                    try
                                    {
                                        await _imageFileService.WriteBytesAsync(currentImage, resizedImageFileStream.ToArray());

                                        LastFile = currentImage;
                                    }
                                    catch (Contract.Exceptions.UnauthorizedAccessException)
                                    {
                                        //log the UnauthorizedAccessException
                                        _loggerService?.LogEvent(nameof(ResizeImages), new Dictionary <String, String>()
                                        {
                                            { nameof(Contract.Exceptions.UnauthorizedAccessException), $"{true}" },
                                        });
                                        //we can't override the current file try for the next files saveAs
                                        action = ImageAction.SaveAs;
                                        await ShowPermissionDeniedDialog(progressBarDialog);

                                        ImageFile File = await _imageFileService.PickSaveFileAsync(currentImage.Path, suggestedFileName);

                                        if (null != File)
                                        {
                                            //try to apply the new storagefolder (if the user selected a new location)
                                            targetStorageFolder = Path.GetDirectoryName(File.Path);

                                            await _imageFileService.WriteBytesAsync(File, resizedImageFileStream.ToArray());

                                            LastFile = File;
                                        }
                                    }
                                } //create new ImageStoreage
                                else if (action.Equals(ImageAction.SaveAs))
                                {
                                    ImageFile imageFile = null;
                                    try
                                    {
                                        //if the user enabled the option "save images to same folder"
                                        if (Settings.SaveFilesForSaveAsInSameFolder && !AppStartType.AppIsShareTarget.Equals(_appStartType))
                                        {
                                            targetStorageFolder = Path.GetDirectoryName(currentImage.Path);
                                        }
                                        if (String.IsNullOrEmpty(targetStorageFolder))
                                        {
                                            if (SingleFile)
                                            {
                                                //get default path
                                                imageFile = await _imageFileService.PickSaveFileAsync(currentImage.Path, suggestedFileName);
                                            }
                                            else
                                            {
                                                imageFile = await _imageFileService.PickSaveFolderAsync(currentImage.Path, suggestedFileName);
                                            }
                                            if (imageFile == null)
                                            {
                                                //if user canceled dialog try again
                                                imageFile = await _imageFileService.PickSaveFileAsync(currentImage.Path, suggestedFileName);
                                            }
                                            //File can be null when user aborted picksavefile dialog
                                            if (imageFile != null)
                                            {
                                                targetStorageFolder = Path.GetDirectoryName(imageFile.Path);
                                                await _imageFileService.WriteBytesAsync(imageFile, resizedImageFileStream.ToArray());

                                                LastFile = imageFile;
                                            }
                                        }
                                        else
                                        {
                                            await _imageFileService.WriteBytesAsync(targetStorageFolder, suggestedFileName, resizedImageFileStream.ToArray());
                                        }
                                    }
                                    catch (FileNotFoundException)
                                    {
                                        //happens if the targetStorageFolder from the settings was removed (or renamed) meanwhile
                                        _loggerService?.LogEvent(nameof(ResizeImages), new Dictionary <String, String>()
                                        {
                                            { nameof(FileNotFoundException), true.ToString() },
                                        });
                                        //happens if the targetStorageFolder was removed meanwhile
                                        Settings.DefaultSaveAsTargetFolder = String.Empty;
                                        //tell the user to save the file in an other location
                                        imageFile = await _imageFileService.PickSaveFileAsync(currentImage.Path, suggestedFileName);

                                        //try to apply the new storagefolder (if the user selected a new location)
                                        if (imageFile != null && Path.GetDirectoryName(targetStorageFolder) != Path.GetDirectoryName(imageFile.Path))
                                        {
                                            targetStorageFolder = Path.GetDirectoryName(imageFile.Path);
                                            await _imageFileService.WriteBytesAsync(imageFile, resizedImageFileStream.ToArray());
                                        }
                                    }
                                    catch (Contract.Exceptions.UnauthorizedAccessException)
                                    {
                                        //log the UnauthorizedAccessException
                                        _loggerService?.LogEvent(nameof(ResizeImages), new Dictionary <String, String>()
                                        {
                                            { nameof(Contract.Exceptions.UnauthorizedAccessException), true.ToString() },
                                        });
                                        //tell the user to save the file in an other location
                                        imageFile = await _imageFileService.PickSaveFileAsync(currentImage.Path, suggestedFileName);

                                        //try to apply the new storagefolder (if the user selected a new location)
                                        if (imageFile != null && Path.GetDirectoryName(targetStorageFolder) != Path.GetDirectoryName(imageFile.Path))
                                        {
                                            targetStorageFolder = Path.GetDirectoryName(imageFile.Path);
                                            await _imageFileService.WriteBytesAsync(imageFile, resizedImageFileStream.ToArray());
                                        }
                                        await ShowPermissionDeniedDialog(progressBarDialog);
                                    }
                                    if (null != imageFile)
                                    {
                                        LastFile = imageFile;
                                    }
                                    _loggerService?.LogEvent(nameof(ResizeImages), new Dictionary <String, String>()
                                    {
                                        { nameof(currentImage.Path), $"{currentImage.Path}" }
                                    });
                                }
                                else if (action.Equals(ImageAction.Process))
                                {
                                    String    TempFolder = _applicationService.GetTemporaryFolderPath();
                                    ImageFile temp       = await _imageFileService.WriteBytesAsync(TempFolder, suggestedFileName, resizedImageFileStream.ToArray());

                                    processedImageAction?.Invoke(temp, $"{suggestedFileName}");
                                }
                                //open resized image depending whether only one image is resized and the user enabled this option
                                if (SingleFile && LastFile != null && action != ImageAction.Process &&
                                    _localSettings.Settings.EnabledOpenSingleFileAfterResize)
                                {
                                    OpenFileCommand.Execute(LastFile);
                                }
                            }
                            currentImage?.Stream?.Dispose();
                        }
                        catch (NotSupportedException e)
                        {
                            _loggerService?.LogException($"{nameof(ResizeImages)}{nameof(ImageFiles)}", e,
                                                         new Dictionary <string, string>()
                            {
                                { nameof(suggestedFileName), suggestedFileName }
                            });
                            await _pageDialogService?.ShowAsync(_resourceLoader.GetString("ImageTypNotSupported"));
                        }
                        catch (InvalidOperationException e)
                        {
                            //for example when enterted width and height is zero. 'Target width 0 and height 0 must be greater than zero.'
                            lastException = e;
                        }
                        catch (FileLoadException e)
                        {
                            //for example The process cannot access the file because it is being used by another process.
                            lastException = e;
                        }
                        catch (UnknownImageFormatException e)
                        {
                            lastException = e;
                        }
                        catch (Exception e)
                        {
                            lastException = e;
                            _loggerService?.LogException($"{nameof(ResizeImages)}{nameof(ImageFiles)}", e);
                        }
                        if (progressBarDialog != null)
                        {
                            progressBarDialog.ProcessedItems++;
                            if (progressBarDialog.AbortedClicked())
                            {
                                _loggerService?.LogEvent(nameof(IResizeService.ResizeAsync), new Dictionary <String, String>()
                                {
                                    { nameof(progressBarDialog.AbortedClicked), Boolean.TrueString }
                                });
                                return(false);
                            }
                        }
                    }
                    if (_localSettings != null && _localSettings.Settings.ShowSuccessMessage && LastFile != null)
                    {
                        await _pageDialogService?.ShowAsync(GenerateSuccess(LastFile));
                    }
                    if (IsShareTarget)
                    {
                        _shareService.EndShareTargetOperation();
                    }
                    Resizing = false;
                    if (lastException != null)
                    {
                        if (lastException is InvalidOperationException || lastException is FileLoadException)
                        {
                            await _pageDialogService.ShowAsync(lastException.Message);
                        }
                        if (lastException is UnknownImageFormatException)
                        {
                            String message = _resourceLoader.GetString("UnknownImageFormatException");
                            if (!String.IsNullOrEmpty(message))
                            {
                                message = String.Format(message, string.Join(", ", _imageFileService.FileTypeFilter));
                                await _pageDialogService.ShowAsync(message);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _loggerService?.LogException(nameof(ResizeImages), e);
                _loggerService?.LogEvent(nameof(IResizeService.ResizeAsync), new Dictionary <String, String>()
                {
                    { "ResizeFinished", "false" }
                });
                return(false);
            }
            finally
            {
                progressBarDialog?.Stop();
                Resizing = false;
            }
            //log image size
            _loggerService?.LogEvent(nameof(IResizeService.ResizeAsync), new Dictionary <String, String>()
            {
                { "ResizeFinished", "true" }
            });
            return(true);
        }
示例#25
0
 public ImageController()
 {
     _imageAction = new ImageAction();
 }
示例#26
0
 public void Setup()
 {
     ImageProviderMock = new Mock <IImageProvider>();
     Action            = new ImageAction(ImageProviderMock.Object, string.Empty);
 }