OSDN Git Service

自動プロパティを使用する (IDE0032)
[opentween/open-tween.git] / OpenTween / MemoryImage.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2013 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
4 //
5 // This file is part of OpenTween.
6 //
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
10 // any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
21
22 using System;
23 using System.Collections.Generic;
24 using System.Linq;
25 using System.Runtime.InteropServices;
26 using System.Runtime.Serialization;
27 using System.Text;
28 using System.Diagnostics.CodeAnalysis;
29 using System.Drawing;
30 using System.IO;
31 using System.Threading.Tasks;
32 using System.Drawing.Imaging;
33
34 namespace OpenTween
35 {
36     /// <summary>
37     /// Image と Stream を対に保持するためのクラス
38     /// </summary>
39     /// <remarks>
40     /// Image.FromStream() を使用して Image を生成する場合、
41     /// Image を破棄するまでの間は元となった Stream を破棄できないためその対策として使用する。
42     /// </remarks>
43     public class MemoryImage : ICloneable, IDisposable, IEquatable<MemoryImage>
44     {
45         private readonly Image image;
46
47         /// <exception cref="InvalidImageException">
48         /// ストリームから読みだされる画像データが不正な場合にスローされる
49         /// </exception>
50         protected MemoryImage(MemoryStream stream)
51         {
52             try
53             {
54                 this.image = Image.FromStream(stream);
55             }
56             catch (ArgumentException e)
57             {
58                 stream.Dispose();
59                 throw new InvalidImageException("Invalid image", e);
60             }
61             catch (OutOfMemoryException e)
62             {
63                 // GDI+ がサポートしない画像形式で OutOfMemoryException がスローされる場合があるらしい
64                 stream.Dispose();
65                 throw new InvalidImageException("Invalid image?", e);
66             }
67             catch (ExternalException e)
68             {
69                 // 「GDI+ で汎用エラーが発生しました」という大雑把な例外がスローされる場合があるらしい
70                 stream.Dispose();
71                 throw new InvalidImageException("Invalid image?", e);
72             }
73             catch (Exception)
74             {
75                 stream.Dispose();
76                 throw;
77             }
78
79             this.Stream = stream;
80         }
81
82         /// <summary>
83         /// MemoryImage が保持している画像
84         /// </summary>
85         public Image Image
86         {
87             get
88             {
89                 if (this.IsDisposed)
90                     throw new ObjectDisposedException("this");
91
92                 return this.image;
93             }
94         }
95
96         /// <summary>
97         /// MemoryImage が保持している画像のストリーム
98         /// </summary>
99         public MemoryStream Stream { get; }
100
101         /// <summary>
102         /// MemoryImage が破棄されているか否か
103         /// </summary>
104         public bool IsDisposed { get; private set; } = false;
105
106         /// <summary>
107         /// MemoryImage が保持している画像のフォーマット
108         /// </summary>
109         public ImageFormat ImageFormat
110         {
111             get { return this.Image.RawFormat; }
112         }
113
114         /// <summary>
115         /// MemoryImage が保持している画像のフォーマットに相当する拡張子 (ピリオド付き)
116         /// </summary>
117         public string ImageFormatExt
118         {
119             get
120             {
121                 var format = this.ImageFormat;
122
123                 // ImageFormat は == で正しく比較できないため Equals を使用する必要がある
124                 if (format.Equals(ImageFormat.Bmp))
125                     return ".bmp";
126                 if (format.Equals(ImageFormat.Emf))
127                     return ".emf";
128                 if (format.Equals(ImageFormat.Gif))
129                     return ".gif";
130                 if (format.Equals(ImageFormat.Icon))
131                     return ".ico";
132                 if (format.Equals(ImageFormat.Jpeg))
133                     return ".jpg";
134                 if (format.Equals(ImageFormat.MemoryBmp))
135                     return ".bmp";
136                 if (format.Equals(ImageFormat.Png))
137                     return ".png";
138                 if (format.Equals(ImageFormat.Tiff))
139                     return ".tiff";
140                 if (format.Equals(ImageFormat.Wmf))
141                     return ".wmf";
142
143                 // 対応する形式がなければ空文字列を返す
144                 // (上記以外のフォーマットは Image.FromStream を通過できないため、ここが実行されることはまず無い)
145                 return string.Empty;
146             }
147         }
148
149         /// <summary>
150         /// MemoryImage インスタンスを複製します
151         /// </summary>
152         /// <remarks>
153         /// メソッド実行中にストリームのシークが行われないよう注意して下さい。
154         /// 特に PictureBox で Gif アニメーションを表示している場合は Enabled に false をセットするなどして更新を止めて下さい。
155         /// </remarks>
156         /// <returns>複製された MemoryImage</returns>
157         public MemoryImage Clone()
158         {
159             this.Stream.Seek(0, SeekOrigin.Begin);
160
161             return MemoryImage.CopyFromStream(this.Stream);
162         }
163
164         /// <summary>
165         /// MemoryImage インスタンスを非同期に複製します
166         /// </summary>
167         /// <remarks>
168         /// メソッド実行中にストリームのシークが行われないよう注意して下さい。
169         /// 特に PictureBox で Gif アニメーションを表示している場合は Enabled に false をセットするなどして更新を止めて下さい。
170         /// </remarks>
171         /// <returns>複製された MemoryImage を返すタスク</returns>
172         public Task<MemoryImage> CloneAsync()
173         {
174             this.Stream.Seek(0, SeekOrigin.Begin);
175
176             return MemoryImage.CopyFromStreamAsync(this.Stream);
177         }
178
179         public override int GetHashCode()
180         {
181             using (var sha1service = new System.Security.Cryptography.SHA1CryptoServiceProvider())
182             {
183                 var hash = sha1service.ComputeHash(this.Stream.GetBuffer(), 0, (int)this.Stream.Length);
184                 return Convert.ToBase64String(hash).GetHashCode();
185             }
186         }
187
188         public override bool Equals(object other)
189         {
190             return this.Equals(other as MemoryImage);
191         }
192
193         public bool Equals(MemoryImage other)
194         {
195             if (object.ReferenceEquals(this, other))
196                 return true;
197
198             if (other == null)
199                 return false;
200
201             // それぞれが保持する MemoryStream の内容が等しいことを検証する
202
203             var selfLength = this.Stream.Length;
204             var otherLength = other.Stream.Length;
205
206             if (selfLength != otherLength)
207                 return false;
208
209             var selfBuffer = this.Stream.GetBuffer();
210             var otherBuffer = other.Stream.GetBuffer();
211
212             for (var pos = 0L; pos < selfLength; pos++)
213             {
214                 if (selfBuffer[pos] != otherBuffer[pos])
215                     return false;
216             }
217
218             return true;
219         }
220
221         object ICloneable.Clone()
222         {
223             return this.Clone();
224         }
225
226         protected virtual void Dispose(bool disposing)
227         {
228             if (this.IsDisposed) return;
229
230             if (disposing)
231             {
232                 this.Image.Dispose();
233                 this.Stream.Dispose();
234             }
235
236             this.IsDisposed = true;
237         }
238
239         public void Dispose()
240         {
241             this.Dispose(true);
242
243             // 明示的にDisposeが呼ばれた場合はファイナライザを使用しない
244             GC.SuppressFinalize(this);
245         }
246
247         ~MemoryImage()
248             => this.Dispose(false);
249
250         /// <summary>
251         /// 指定された Stream から MemoryImage を作成します。
252         /// </summary>
253         /// <remarks>
254         /// ストリームの内容はメモリ上に展開した後に使用されるため、
255         /// 引数に指定した Stream を MemoryImage より先に破棄しても問題ありません。
256         /// </remarks>
257         /// <param name="stream">読み込む対象となる Stream</param>
258         /// <returns>作成された MemoryImage</returns>
259         /// <exception cref="InvalidImageException">不正な画像データが入力された場合</exception>
260         public static MemoryImage CopyFromStream(Stream stream)
261         {
262             MemoryStream memstream = null;
263             try
264             {
265                 memstream = new MemoryStream();
266
267                 stream.CopyTo(memstream);
268
269                 return new MemoryImage(memstream);
270             }
271             catch
272             {
273                 memstream?.Dispose();
274                 throw;
275             }
276         }
277
278         /// <summary>
279         /// 指定された Stream から MemoryImage を非同期に作成します。
280         /// </summary>
281         /// <remarks>
282         /// ストリームの内容はメモリ上に展開した後に使用されるため、
283         /// 引数に指定した Stream を MemoryImage より先に破棄しても問題ありません。
284         /// </remarks>
285         /// <param name="stream">読み込む対象となる Stream</param>
286         /// <returns>作成された MemoryImage を返すタスク</returns>
287         /// <exception cref="InvalidImageException">不正な画像データが入力された場合</exception>
288         public async static Task<MemoryImage> CopyFromStreamAsync(Stream stream)
289         {
290             MemoryStream memstream = null;
291             try
292             {
293                 memstream = new MemoryStream();
294
295                 await stream.CopyToAsync(memstream).ConfigureAwait(false);
296
297                 return new MemoryImage(memstream);
298             }
299             catch
300             {
301                 memstream?.Dispose();
302                 throw;
303             }
304         }
305
306         /// <summary>
307         /// 指定されたバイト列から MemoryImage を作成します。
308         /// </summary>
309         /// <param name="bytes">読み込む対象となるバイト列</param>
310         /// <returns>作成された MemoryImage</returns>
311         /// <exception cref="InvalidImageException">不正な画像データが入力された場合</exception>
312         public static MemoryImage CopyFromBytes(byte[] bytes)
313         {
314             MemoryStream memstream = null;
315             try
316             {
317                 memstream = new MemoryStream(bytes);
318                 return new MemoryImage(memstream);
319             }
320             catch
321             {
322                 memstream?.Dispose();
323                 throw;
324             }
325         }
326
327         /// <summary>
328         /// Image インスタンスから MemoryImage を作成します
329         /// </summary>
330         /// <remarks>
331         /// PNG 画像として描画し直す処理を含むため、極力 Stream や byte[] を渡す他のメソッドを使用すべきです
332         /// </remarks>
333         /// <param name="image">対象となる画像</param>
334         /// <returns>作成された MemoryImage</returns>
335         public static MemoryImage CopyFromImage(Image image)
336         {
337             MemoryStream memstream = null;
338             try
339             {
340                 memstream = new MemoryStream();
341
342                 image.Save(memstream, ImageFormat.Png);
343
344                 return new MemoryImage(memstream);
345             }
346             catch
347             {
348                 memstream?.Dispose();
349                 throw;
350             }
351         }
352     }
353
354     /// <summary>
355     /// 不正な画像データに対してスローされる例外
356     /// </summary>
357     [Serializable]
358     public class InvalidImageException : Exception
359     {
360         public InvalidImageException() { }
361         public InvalidImageException(string message) : base(message) { }
362         public InvalidImageException(string message, Exception innerException) : base(message, innerException) { }
363         protected InvalidImageException(SerializationInfo info, StreamingContext context) : base(info, context) { }
364     }
365 }