-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
208 lines (172 loc) · 5.72 KB
/
Copy pathProgram.cs
File metadata and controls
208 lines (172 loc) · 5.72 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System.Text.Json;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseStaticFiles();
// In-memory image store (replace with persistent storage for production)
var imageStore = new Dictionary<string, byte[]>();
var imagesPath = Path.Combine(app.Environment.ContentRootPath, "wwwroot", "images");
Directory.CreateDirectory(imagesPath);
// Disabled images tracking
var disabledPath = Path.Combine(imagesPath, "disabled.json");
var disabledIds = new HashSet<string>();
if (File.Exists(disabledPath))
{
disabledIds = JsonSerializer.Deserialize<HashSet<string>>(File.ReadAllText(disabledPath)) ?? new();
}
void SaveDisabled() => File.WriteAllText(disabledPath, JsonSerializer.Serialize(disabledIds));
// String simple endpoint
app.MapGet("/hello", () =>
{
return "Hello from NetFrames API!";
});
// Return enabled image IDs (for embedded client)
app.MapGet("/images/list", () =>
{
var files = Directory.GetFiles(imagesPath, "*.jpg")
.Select(f => Path.GetFileNameWithoutExtension(f))
.Where(id => !disabledIds.Contains(id))
.ToArray();
return Results.Ok(files);
});
// Return all images with enabled/disabled status (for WebPortal)
app.MapGet("/images/list/all", () =>
{
var files = Directory.GetFiles(imagesPath, "*.jpg")
.Select(f => Path.GetFileNameWithoutExtension(f))
.Select(id => new { id, enabled = !disabledIds.Contains(id) })
.ToArray();
return Results.Ok(files);
});
// Toggle image visibility
app.MapPost("/images/{id}/toggle", (string id) =>
{
var filePath = Path.Combine(imagesPath, $"{id}.jpg");
if (!File.Exists(filePath))
return Results.NotFound();
bool enabled;
if (disabledIds.Contains(id))
{
disabledIds.Remove(id);
enabled = true;
}
else
{
disabledIds.Add(id);
enabled = false;
}
SaveDisabled();
return Results.Ok(new { id, enabled });
});
// Get image metadata
app.MapGet("/images/{id}/info", async (string id) =>
{
var filePath = Path.Combine(imagesPath, $"{id}.jpg");
if (!File.Exists(filePath))
return Results.NotFound();
var fileInfo = new FileInfo(filePath);
using var image = await Image.LoadAsync(filePath);
return Results.Ok(new
{
id,
extension = ".jpg",
uploadedAt = fileInfo.CreationTimeUtc,
width = image.Width,
height = image.Height
});
});
// Get image endpoint (serve from disk)
app.MapGet("/images/{id}", async (string id, int? width, int? height) =>
{
var filePath = Path.Combine(imagesPath, $"{id}.jpg");
Console.WriteLine($"Requested image id: {id}");
Console.WriteLine($"File path: {filePath}");
Console.WriteLine($"Width: {width}, Height: {height}");
if (!File.Exists(filePath))
{
Console.WriteLine("File not found.");
return Results.NotFound();
}
try
{
if (width is null && height is null)
{
Console.WriteLine("Returning original image.");
return Results.File(filePath, "image/jpeg");
}
using var image = await Image.LoadAsync(filePath);
if (image.Width != width && image.Height != height)
{
float screenAspect = (float)((float)width! / height!);
float imageAspect = (float)image.Width / image.Height;
if (screenAspect == imageAspect)
{
image.Mutate(x => x.Resize(width ?? 0, height ?? 0));
}
else
{
Rectangle cropRect = new Rectangle();
if (screenAspect < imageAspect)
{
image.Mutate(x => x.Resize(0, height.Value));
cropRect = new Rectangle((int)((image.Width - width) / 2), 0, (int)width, (int)height);
}
else
{
image.Mutate(x => x.Resize(width.Value, 0));
cropRect = new Rectangle(0, (int)((image.Height - height) / 2), (int)width, (int)height);
}
Console.WriteLine($"Cropping and resizing to {width}x{height}");
image.Mutate(x => x.Crop(cropRect));
}
}
var ms = new MemoryStream();
await image.SaveAsJpegAsync(ms);
ms.Position = 0;
Console.WriteLine("Returning processed image.");
return Results.File(ms, "image/jpeg");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
return Results.Problem("Internal Server Error");
}
});
// Upload image endpoint (save to disk)
app.MapPost("/images/upload", async (HttpRequest request) =>
{
if (!request.HasFormContentType)
return Results.BadRequest("Form content type required.");
var form = await request.ReadFormAsync();
var file = form.Files["image"];
if (file == null || file.Length == 0)
return Results.BadRequest("No image uploaded.");
var id = Guid.NewGuid().ToString();
var fileName = $"{id}.jpg";
var filePath = Path.Combine(imagesPath, fileName);
await using (var stream = File.Create(filePath))
{
await file.CopyToAsync(stream);
}
return Results.Ok(new { id, fileName });
})
.WithName("UploadImage");
// Delete image endpoint (remove from disk)
app.MapDelete("/images/{id}", (string id) =>
{
var filePath = Path.Combine(imagesPath, $"{id}.jpg");
if (!File.Exists(filePath))
{
return Results.NotFound();
}
File.Delete(filePath);
if (disabledIds.Remove(id)) SaveDisabled();
return Results.Ok(new { message = $"Image {id} deleted." });
});
app.Run();