Image と Stream を対に保持するためのクラス
Image.FromStream() を使用して Image を生成する場合、 Image を破棄するまでの間は元となった Stream を破棄できないためその対策として使用する。
Inheritance: IDisposable
Ejemplo n.º 1
0
        public void BeginSelection_FilePathTest()
        {
            using var twitter       = new Twitter();
            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
            twitter.Initialize("", "", "", 0L);
            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

            var images = new[] { "Resources/re.gif" };

            Assert.Raises <EventArgs>(
                x => mediaSelector.BeginSelecting += x,
                x => mediaSelector.BeginSelecting -= x,
                () => mediaSelector.BeginSelection(images)
                );

            Assert.True(mediaSelector.Visible);
            Assert.True(mediaSelector.Enabled);

            // 2 ページ目まで選択可能な状態
            var pages = mediaSelector.ImagePageCombo.Items;

            Assert.Equal(new[] { "1", "2" }, pages.Cast <object>().Select(x => x.ToString()));

            // 1 ページ目が表示されている
            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
            Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);

            using var imageStream = File.OpenRead("Resources/re.gif");
            using var image       = MemoryImage.CopyFromStream(imageStream);
            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
        }
Ejemplo n.º 2
0
        private MemoryImageMediaItem CreateMemoryImageMediaItem(Image image, bool noMsgBox)
        {
            if (image == null)
            {
                return(null);
            }

            MemoryImage memoryImage = null;

            try
            {
                // image から png 形式の MemoryImage を生成
                memoryImage = MemoryImage.CopyFromImage(image);

                return(new MemoryImageMediaItem(memoryImage));
            }
            catch
            {
                memoryImage?.Dispose();

                if (!noMsgBox)
                {
                    MessageBox.Show("Unable to create MemoryImage.");
                }
                return(null);
            }
        }
Ejemplo n.º 3
0
 public MemoryImage CreateImage()
 {
     using (var fs = this.FileInfo.OpenRead())
     {
         return(MemoryImage.CopyFromStream(fs));
     }
 }
Ejemplo n.º 4
0
        public void ImagePathInput_ReplaceFileMediaItemTest()
        {
            using var twitter       = new Twitter();
            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
            twitter.Initialize("", "", "", 0L);
            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

            mediaSelector.BeginSelection(new[] { "Resources/re.gif" });

            // 既に入力されているファイルパスの画像
            var image1 = mediaSelector.ImageSelectedPicture.Image;

            // 別の画像のファイルパスを入力
            mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
            TestUtils.Validate(mediaSelector.ImagefilePathText);

            // 入力したパスの画像が表示される
            using (var imageStream = File.OpenRead("Resources/re1.png"))
            {
                using var image2 = MemoryImage.CopyFromStream(imageStream);
                Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
            }

            // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
            Assert.True(image1 !.IsDisposed);
        }
Ejemplo n.º 5
0
        public void BeginSelection_MemoryImageTest()
        {
            using var twitter       = new Twitter();
            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
            twitter.Initialize("", "", "", 0L);
            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

            using (var bitmap = new Bitmap(width: 200, height: 200))
            {
                Assert.Raises <EventArgs>(
                    x => mediaSelector.BeginSelecting += x,
                    x => mediaSelector.BeginSelecting -= x,
                    () => mediaSelector.BeginSelection(bitmap)
                    );
            }

            Assert.True(mediaSelector.Visible);
            Assert.True(mediaSelector.Enabled);

            // 2 ページ目まで選択可能な状態
            var pages = mediaSelector.ImagePageCombo.Items;

            Assert.Equal(new[] { "1", "2" }, pages.Cast <object>().Select(x => x.ToString()));

            // 1 ページ目が表示されている
            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
            Assert.Matches(@"^<>MemoryImage://\d+.png$", mediaSelector.ImagefilePathText.Text);

            using (var bitmap = new Bitmap(width: 200, height: 200))
            {
                using var image = MemoryImage.CopyFromImage(bitmap);
                Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
            }
        }
Ejemplo n.º 6
0
        public void ImagePathInput_Test()
        {
            using (var twitter = new Twitter())
                using (var mediaSelector = new MediaSelector {
                    Visible = false, Enabled = false
                })
                {
                    twitter.Initialize("", "", "", 0L);
                    mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
                    mediaSelector.BeginSelection();

                    // 画像のファイルパスを入力
                    mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
                    TestUtils.Validate(mediaSelector.ImagefilePathText);

                    // 入力したパスの画像が表示される
                    using (var imageStream = File.OpenRead("Resources/re1.png"))
                        using (var image = MemoryImage.CopyFromStream(imageStream))
                        {
                            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
                        }

                    // 2 ページ目まで選択可能な状態
                    var pages = mediaSelector.ImagePageCombo.Items;
                    Assert.Equal(new[] { "1", "2" }, pages.Cast <object>().Select(x => x.ToString()));
                }
        }
Ejemplo n.º 7
0
        private async Task SetUserImageAsync(string imageUri, CancellationToken cancellationToken)
        {
            var oldImage = this.UserPicture.Image;

            this.UserPicture.Image = null;
            oldImage?.Dispose();

            // ProfileImageUrlHttps が null になる場合があるらしい
            // 参照: https://sourceforge.jp/ticket/browse.php?group_id=6526&tid=33871
            if (imageUri == null)
            {
                return;
            }

            await this.UserPicture.SetImageFromTask(async() =>
            {
                var uri = imageUri.Replace("_normal", "_bigger");

                using (var imageStream = await Networking.Http.GetStreamAsync(uri).ConfigureAwait(false))
                {
                    var image = await MemoryImage.CopyFromStreamAsync(imageStream)
                                .ConfigureAwait(false);

                    if (cancellationToken.IsCancellationRequested)
                    {
                        image.Dispose();
                        throw new OperationCanceledException(cancellationToken);
                    }

                    return(image);
                }
            });
        }
Ejemplo n.º 8
0
        public void BeginSelection_MultiImageTest()
        {
            using (var twitter = new Twitter())
                using (var mediaSelector = new MediaSelector {
                    Visible = false, Enabled = false
                })
                {
                    twitter.Initialize("", "", "", 0L);
                    mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

                    var images = new[] { "Resources/re.gif", "Resources/re1.png" };
                    mediaSelector.BeginSelection(images);

                    // 3 ページ目まで選択可能な状態
                    var pages = mediaSelector.ImagePageCombo.Items;
                    Assert.Equal(new[] { "1", "2", "3" }, pages.Cast <object>().Select(x => x.ToString()));

                    // 1 ページ目が表示されている
                    Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
                    Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);

                    using (var imageStream = File.OpenRead("Resources/re.gif"))
                        using (var image = MemoryImage.CopyFromStream(imageStream))
                        {
                            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
                        }
                }
        }
Ejemplo n.º 9
0
        private async Task LoadUserIconAsync(Uri imageUri, long userId)
        {
            var oldImage = this.UserIcon.Image;

            this.UserIcon.Image = null;
            oldImage?.Dispose();

            await this.UserIcon.SetImageFromTask(async() =>
            {
                var uri = imageUri.AbsoluteUri.Replace("_normal", "_bigger");

                using (var imageStream = await Networking.Http.GetStreamAsync(uri))
                {
                    var image = await MemoryImage.CopyFromStreamAsync(imageStream);

                    // 画像の読み込み中に選択中のユーザーが変化していたらキャンセルとして扱う
                    var selectedUser = (UserInfo)this.UserList.SelectedItem;
                    if (selectedUser.Id != userId)
                    {
                        image.Dispose();
                        throw new OperationCanceledException();
                    }

                    return(image);
                }
            });
        }
Ejemplo n.º 10
0
 public void CopyFromImage_Test()
 {
     using (var bitmap = new Bitmap(width: 200, height: 200))
     {
         // MemoryImage をエラー無く作成できることをテストする
         using (var image = MemoryImage.CopyFromImage(bitmap)) { }
     }
 }
Ejemplo n.º 11
0
        public MemoryImageMediaItem(MemoryImage image)
        {
            this._image = image ?? throw new ArgumentNullException(nameof(image));

            var num = Interlocked.Increment(ref _fileNumber);

            this.Path = PathPrefix + num + this._image.ImageFormatExt;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 指定された URL にある画像を非同期に取得するメソッド
        /// </summary>
        /// <param name="address">取得先の URL</param>
        /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
        /// <returns>非同期に画像を取得するタスク</returns>
        public Task <MemoryImage> DownloadImageAsync(string address, bool force = false)
        {
            var cancelToken = this.cancelTokenSource.Token;

            return(Task.Factory.StartNew(() =>
            {
                Task <MemoryImage> cachedImageTask = null;
                lock (this.lockObject)
                {
                    if (force)
                    {
                        this.innerDictionary.Remove(address);
                    }

                    if (this.innerDictionary.ContainsKey(address) && !this.innerDictionary[address].IsFaulted)
                    {
                        cachedImageTask = this.innerDictionary[address];
                    }
                }

                if (cachedImageTask != null)
                {
                    return cachedImageTask;
                }

                cancelToken.ThrowIfCancellationRequested();

                using (var client = new OTWebClient()
                {
                    Timeout = 10000
                })
                {
                    var imageTask = client.DownloadDataAsync(new Uri(address), cancelToken).ContinueWith(t =>
                    {
                        MemoryImage image = null;
                        if (t.Status == TaskStatus.RanToCompletion)
                        {
                            image = MemoryImage.CopyFromBytes(t.Result);
                        }

                        if (t.Exception != null)
                        {
                            t.Exception.Handle(e => e is WebException);
                        }

                        // FIXME: MemoryImage.Dispose() が正しいタイミングで呼ばれるように修正すべき
                        return image;
                    }, cancelToken);

                    lock (this.lockObject)
                    {
                        this.innerDictionary[address] = imageTask;
                    }

                    return imageTask;
                }
            }, cancelToken).Unwrap());
        }
Ejemplo n.º 13
0
 public async Task ImageFormat_GifTest()
 {
     using (var imgStream = File.OpenRead("Resources/re.gif"))
         using (var image = await MemoryImage.CopyFromStreamAsync(imgStream).ConfigureAwait(false))
         {
             Assert.Equal(ImageFormat.Gif, image.ImageFormat);
             Assert.Equal(".gif", image.ImageFormatExt);
         }
 }
Ejemplo n.º 14
0
        public static MemoryImage CreateDummyImage()
        {
            using var bitmap = new Bitmap(100, 100);
            using var stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Png);
            stream.Position = 0;

            return(MemoryImage.CopyFromStream(stream));
        }
Ejemplo n.º 15
0
 public void ImageFormat_CopyFromImageTest()
 {
     using (var bitmap = new Bitmap(width: 200, height: 200))
         using (var image = MemoryImage.CopyFromImage(bitmap))
         {
             // CopyFromImage から作成した MemoryImage は PNG 画像として扱われる
             Assert.Equal(ImageFormat.Png, image.ImageFormat);
             Assert.Equal(".png", image.ImageFormatExt);
         }
 }
Ejemplo n.º 16
0
        private async Task <MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
        {
            using (var response = await Networking.Http.GetAsync(uri, cancelToken).ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();

                using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    return(await MemoryImage.CopyFromStreamAsync(imageStream)
                           .ConfigureAwait(false));
                }
            }
        }
Ejemplo n.º 17
0
        public void PageChange_Test()
        {
            using (var twitter = new Twitter())
                using (var mediaSelector = new MediaSelector {
                    Visible = false, Enabled = false
                })
                {
                    twitter.Initialize("", "", "", 0L);
                    mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

                    var images = new[] { "Resources/re.gif", "Resources/re1.png" };
                    mediaSelector.BeginSelection(images);

                    mediaSelector.ImagePageCombo.SelectedIndex = 0;

                    // 1 ページ目
                    Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
                    Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);

                    using (var imageStream = File.OpenRead("Resources/re.gif"))
                        using (var image = MemoryImage.CopyFromStream(imageStream))
                        {
                            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
                        }

                    mediaSelector.ImagePageCombo.SelectedIndex = 1;

                    // 2 ページ目
                    Assert.Equal("2", mediaSelector.ImagePageCombo.Text);
                    Assert.Equal(Path.GetFullPath("Resources/re1.png"), mediaSelector.ImagefilePathText.Text);

                    using (var imageStream = File.OpenRead("Resources/re1.png"))
                        using (var image = MemoryImage.CopyFromStream(imageStream))
                        {
                            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
                        }

                    mediaSelector.ImagePageCombo.SelectedIndex = 2;

                    // 3 ページ目 (新規ページ)
                    Assert.Equal("3", mediaSelector.ImagePageCombo.Text);
                    Assert.Equal("", mediaSelector.ImagefilePathText.Text);
                    Assert.Null(mediaSelector.ImageSelectedPicture.Image);
                }
        }
Ejemplo n.º 18
0
        public async Task Equals_Test()
        {
            using (var imgStream1 = File.OpenRead("Resources/re.gif"))
                using (var image1 = await MemoryImage.CopyFromStreamAsync(imgStream1).ConfigureAwait(false))
                {
                    using (var imgStream2 = File.OpenRead("Resources/re.gif"))
                        using (var image2 = await MemoryImage.CopyFromStreamAsync(imgStream2).ConfigureAwait(false))
                        {
                            Assert.True(image1.Equals(image2));
                            Assert.True(image2.Equals(image1));
                        }

                    using (var image3 = TestUtils.CreateDummyImage())
                    {
                        Assert.False(image1.Equals(image3));
                        Assert.False(image3.Equals(image1));
                    }
                }
        }
Ejemplo n.º 19
0
        public void ImagePathInput_ReplaceMemoryImageMediaItemTest()
        {
            using (var twitter = new Twitter())
                using (var mediaSelector = new MediaSelector {
                    Visible = false, Enabled = false
                })
                {
                    twitter.Initialize("", "", "", 0L);
                    mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");

                    using (var bitmap = new Bitmap(width: 200, height: 200))
                    {
                        mediaSelector.BeginSelection(bitmap);
                    }

                    // 既に入力されているファイルパスの画像
                    var image1 = mediaSelector.ImageSelectedPicture.Image;

                    // 内部で保持されている MemoryImageMediaItem を取り出す
                    var selectedMedia = mediaSelector.ImagePageCombo.SelectedItem;
                    var mediaProperty = selectedMedia.GetType().GetProperty("Item");
                    var mediaItem     = (MemoryImageMediaItem)mediaProperty.GetValue(selectedMedia);

                    // 別の画像のファイルパスを入力
                    mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
                    TestUtils.Validate(mediaSelector.ImagefilePathText);

                    // 入力したパスの画像が表示される
                    using (var imageStream = File.OpenRead("Resources/re1.png"))
                        using (var image2 = MemoryImage.CopyFromStream(imageStream))
                        {
                            Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
                        }

                    // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
                    Assert.True(image1.IsDisposed);

                    // 参照されなくなった MemoryImageMediaItem も破棄される
                    Assert.True(mediaItem.IsDisposed);
                }
        }
Ejemplo n.º 20
0
        public new Task LoadAsync(string url)
        {
            this._ImageLocation = url;

            if (this.loadAsyncTask != null && !this.loadAsyncTask.IsCompleted)
                this.CancelAsync();

            if (this.expandedInitialImage != null)
                this.Image = this.expandedInitialImage;

            Uri uri;
            try
            {
                uri = new Uri(url);
            }
            catch (UriFormatException)
            {
                uri = new Uri(Path.GetFullPath(url));
            }

            var client = new OTWebClient();

            client.DownloadProgressChanged += (s, e) =>
            {
                this.OnLoadProgressChanged(new ProgressChangedEventArgs(e.ProgressPercentage, e.UserState));
            };

            this.loadAsyncCancelTokenSource = new CancellationTokenSource();
            var cancelToken = this.loadAsyncCancelTokenSource.Token;
            var loadImageTask = client.DownloadDataAsync(uri, cancelToken);

            // UnobservedTaskException イベントを発生させないようにする
            loadImageTask.ContinueWith(t => { var ignore = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);

            var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            return loadImageTask.ContinueWith(t => {
                client.Dispose();

                if (t.IsFaulted) throw t.Exception;

                return MemoryImage.CopyFromBytes(t.Result);
            }, cancelToken)
            .ContinueWith(t =>
            {
                if (!t.IsCanceled)
                {
                    if (t.IsFaulted)
                    {
                        this.Image = this.expandedErrorImage;
                    }
                    else
                    {
                        this.Image = t.Result.Image;
                        this.memoryImage = t.Result;
                    }
                }

                var exp = t.Exception != null ? t.Exception.Flatten() : null;
                this.OnLoadCompleted(new AsyncCompletedEventArgs(exp, t.IsCanceled, null));
            }, uiScheduler);
        }
Ejemplo n.º 21
0
        public new Task LoadAsync(string url)
        {
            this._ImageLocation = url;

            if (this.loadAsyncTask != null && !this.loadAsyncTask.IsCompleted)
            {
                this.CancelAsync();
            }

            this.Image = base.InitialImage;

            Uri uri;

            try
            {
                uri = new Uri(url);
            }
            catch (UriFormatException)
            {
                uri = new Uri(Path.GetFullPath(url));
            }

            var client = new OTWebClient();

            client.DownloadProgressChanged += (s, e) =>
            {
                this.OnLoadProgressChanged(new ProgressChangedEventArgs(e.ProgressPercentage, e.UserState));
            };

            this.loadAsyncCancelTokenSource = new CancellationTokenSource();
            var cancelToken   = this.loadAsyncCancelTokenSource.Token;
            var loadImageTask = client.DownloadDataAsync(uri, cancelToken);

            // UnobservedTaskException イベントを発生させないようにする
            loadImageTask.ContinueWith(t => { var ignore = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);

            var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            return(loadImageTask.ContinueWith(t => {
                client.Dispose();

                if (t.IsFaulted)
                {
                    throw t.Exception;
                }

                return MemoryImage.CopyFromBytes(t.Result);
            }, cancelToken)
                   .ContinueWith(t =>
            {
                if (!t.IsCanceled)
                {
                    if (t.IsFaulted)
                    {
                        this.Image = base.ErrorImage;
                    }
                    else
                    {
                        this.Image = t.Result.Image;
                        this.memoryImage = t.Result;
                    }
                }

                var exp = t.Exception != null ? t.Exception.Flatten() : null;
                this.OnLoadCompleted(new AsyncCompletedEventArgs(exp, t.IsCanceled, null));
            }, uiScheduler));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// MemoryImage インスタンスを非同期に複製します
        /// </summary>
        /// <remarks>
        /// メソッド実行中にストリームのシークが行われないよう注意して下さい。
        /// 特に PictureBox で Gif アニメーションを表示している場合は Enabled に false をセットするなどして更新を止めて下さい。
        /// </remarks>
        /// <returns>複製された MemoryImage を返すタスク</returns>
        public Task <MemoryImage> CloneAsync()
        {
            this.Stream.Seek(0, SeekOrigin.Begin);

            return(MemoryImage.CopyFromStreamAsync(this.Stream));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// MemoryImage インスタンスを複製します
        /// </summary>
        /// <remarks>
        /// メソッド実行中にストリームのシークが行われないよう注意して下さい。
        /// 特に PictureBox で Gif アニメーションを表示している場合は Enabled に false をセットするなどして更新を止めて下さい。
        /// </remarks>
        /// <returns>複製された MemoryImage</returns>
        public MemoryImage Clone()
        {
            this.Stream.Seek(0, SeekOrigin.Begin);

            return(MemoryImage.CopyFromStream(this.Stream));
        }
Ejemplo n.º 24
0
        public MemoryImageMediaItem(Image image)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            // image から png 形式の MemoryImage を生成
            this._image = MemoryImage.CopyFromImage(image);

            var num = Interlocked.Increment(ref _fileNumber);
            this._path = PathPrefix + num + this._image.ImageFormatExt;
        }
Ejemplo n.º 25
0
        protected ThumbnailZoomWindow(MemoryImage thumbnail, ThumbnailInfo thumbInfo, Rectangle startupBounds, Point originPos)
        {
            this.startupBounds = startupBounds;
            this.originPos = originPos;

            using (ControlTransaction.Layout(this, false))
            {
                this.DoubleBuffered = true;

                this.TopMost = true;
                this.FormBorderStyle = FormBorderStyle.None;
                this.ShowInTaskbar = false;

                this.StartPosition = FormStartPosition.Manual;
                this.Bounds = startupBounds;

                this.Capture = true;

                this.MouseMove += ThumbnailZoomWindow_MouseMove;
                this.MouseUp += ThumbnailZoomWindow_MouseUp;

                var picbox = new OTPictureBox()
                {
                    Name = "picbox",
                    Image = thumbnail,
                    Tag = thumbInfo,
                    SizeMode = PictureBoxSizeMode.Zoom,
                    WaitOnLoad = false,
                    Dock = DockStyle.Fill,
                };
                this.Controls.Add(picbox);

                picbox.MouseMove += ThumbnailZoomWindow_MouseMove;
                picbox.MouseUp += ThumbnailZoomWindow_MouseUp;
            }
        }
Ejemplo n.º 26
0
        private void ImageFromSelectedFile(int index, string fileName, bool suppressMsgBox)
        {
            var serviceName = this.ServiceName;

            if (string.IsNullOrEmpty(serviceName))
            {
                return;
            }

            var selectedIndex = ImagePageCombo.SelectedIndex;

            if (index < 0)
            {
                index = selectedIndex;
            }

            if (index >= ImagePageCombo.Items.Count)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            var imageService   = this.pictureService[serviceName];
            var isSelectedPage = (index == selectedIndex);

            if (isSelectedPage)
            {
                this.ClearImageSelectedPicture();
            }

            if (string.IsNullOrEmpty(fileName))
            {
                ClearImagePage(index);
                return;
            }

            try
            {
                FileInfo fl  = new FileInfo(fileName);
                string   ext = fl.Extension;

                if (!imageService.CheckFileExtension(ext))
                {
                    //画像以外の形式
                    ClearImagePage(index);
                    if (!suppressMsgBox)
                    {
                        MessageBox.Show(
                            string.Format(Properties.Resources.PostPictureWarn3, serviceName, MakeAvailableServiceText(ext, fl.Length), ext, fl.Name),
                            Properties.Resources.PostPictureWarn4,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                    return;
                }

                if (!imageService.CheckFileSize(ext, fl.Length))
                {
                    // ファイルサイズが大きすぎる
                    ClearImagePage(index);
                    if (!suppressMsgBox)
                    {
                        MessageBox.Show(
                            string.Format(Properties.Resources.PostPictureWarn5, serviceName, MakeAvailableServiceText(ext, fl.Length), fl.Name),
                            Properties.Resources.PostPictureWarn4,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                    return;
                }

                try
                {
                    using (var fs = File.OpenRead(fileName))
                    {
                        var image = MemoryImage.CopyFromStream(fs);
                        if (isSelectedPage)
                        {
                            ImageSelectedPicture.Image = image;
                        }
                        else
                        {
                            image.Dispose();  //画像チェック後は使わないので破棄する
                        }
                    }
                    SetImagePage(index, fileName, MyCommon.UploadFileType.Picture);
                }
                catch (InvalidImageException)
                {
                    SetImagePage(index, fileName, MyCommon.UploadFileType.MultiMedia);
                }
            }
            catch (FileNotFoundException)
            {
                ClearImagePage(index);
                if (!suppressMsgBox)
                {
                    MessageBox.Show("File not found.");
                }
            }
            catch (Exception)
            {
                ClearImagePage(index);
                if (!suppressMsgBox)
                {
                    MessageBox.Show("The type of this file is not image.");
                }
            }
        }
Ejemplo n.º 27
0
        public MemoryImageMediaItem(MemoryImage image)
        {
            if (image == null)
                throw new ArgumentNullException(nameof(image));

            this._image = image;

            var num = Interlocked.Increment(ref _fileNumber);
            this.Path = PathPrefix + num + this._image.ImageFormatExt;
        }