-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystemImage.cs
More file actions
141 lines (115 loc) · 3.07 KB
/
FileSystemImage.cs
File metadata and controls
141 lines (115 loc) · 3.07 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
namespace PictureView;
public class FileSystemImage : ObservableObject, IDisposable
{
private bool isImageOutdated, isImageLoaded;
private MemoryStream? stream;
private IImage? image;
public FileInfo File { get; }
public bool IsImageOutdated
{
get => isImageOutdated;
private set
{
if (value == isImageOutdated) return;
isImageOutdated = value;
OnPropertyChanged();
}
}
public bool IsImageLoaded
{
get => isImageLoaded;
private set
{
if (value == isImageLoaded) return;
isImageLoaded = value;
OnPropertyChanged();
}
}
public long? DataSize => stream?.Length;
public IImage? Image
{
get => image;
private set
{
if (value == image) return;
image = value;
OnPropertyChanged();
}
}
public FileSystemImage(FileInfo file)
{
File = file;
IsImageLoaded = false;
stream = null;
Image = null;
}
public async Task LoadBytes()
{
try
{
File.Refresh();
if (File.Length < 100000000)
{
MemoryStream destStream = new MemoryStream();
await using Stream srcStream = System.IO.File.OpenRead(File.FullName);
await srcStream.CopyToAsync(destStream);
Stream? oldStream = stream;
stream = destStream;
IsImageOutdated = oldStream == null || !SequenceEqual(oldStream, destStream);
await (oldStream?.DisposeAsync() ?? ValueTask.CompletedTask);
}
else Dispose();
}
catch
{
Dispose();
}
}
private static bool SequenceEqual(Stream stream1, Stream stream2)
{
if (stream1.Length != stream2.Length) return false;
stream1.Seek(0, SeekOrigin.Begin);
stream2.Seek(0, SeekOrigin.Begin);
const int bufferSize = 1000;
byte[] buffer1 = new byte[bufferSize], buffer2 = new byte[bufferSize];
while (stream1.Position < stream1.Length)
{
int read1 = stream1.Read(buffer1, 0, bufferSize);
int read2 = stream2.Read(buffer2, 0, bufferSize);
if (read1 != read2 || !buffer1.Take(read1).SequenceEqual(buffer2.Take(read2))) return false;
}
return true;
}
public void LoadImage()
{
try
{
Image = stream != null ? Utils.LoadBitmap(stream) : null;
}
catch
{
Image = null;
}
finally
{
IsImageLoaded = true;
}
IsImageOutdated = false;
}
public byte[]? GetImageBytes()
{
return stream?.ToArray();
}
public void Dispose()
{
stream?.Dispose();
stream = null;
Image = null;
}
}