-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBitmapDataStream.cs
99 lines (63 loc) · 2.58 KB
/
BitmapDataStream.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace Gsemac.Drawing {
public class BitmapDataStream :
Stream {
// Public members
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => bitmapData.Stride * bitmap.Height;
public override long Position {
get => position;
set => throw new NotSupportedException();
}
public BitmapDataStream(Bitmap bitmap) {
if (bitmap is null)
throw new ArgumentNullException(nameof(bitmap));
if (ImageUtilities.HasIndexedPixelFormat(bitmap)) {
this.bitmap = (Bitmap)ImageUtilities.ConvertToNonIndexedPixelFormat(bitmap, disposeSourceImage: false);
this.disposeBitmap = true;
}
else {
this.bitmap = bitmap;
}
this.bitmapData = this.bitmap.LockBits(new Rectangle(0, 0, this.bitmap.Width, this.bitmap.Height), ImageLockMode.ReadOnly, this.bitmap.PixelFormat);
}
public override int Read(byte[] buffer, int offset, int count) {
if (position >= Length)
return 0;
if (position + count > Length)
count = (int)(Length - position);
IntPtr ptr = IntPtr.Add(bitmapData.Scan0, (int)position);
Marshal.Copy(ptr, buffer, offset, count);
position = Math.Min(position + count, Length);
return count;
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Close() {
// Unlock the bitmap.
bitmap.UnlockBits(bitmapData);
base.Close();
}
public override void Flush() { }
// Protected members
protected override void Dispose(bool disposing) {
if (disposing) {
if (disposeBitmap)
bitmap.Dispose();
}
base.Dispose(disposing);
}
// Private members
private readonly Bitmap bitmap;
private readonly BitmapData bitmapData;
private readonly bool disposeBitmap = false;
private long position = 0;
}
}