-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageService.cs
More file actions
83 lines (66 loc) · 2.36 KB
/
ImageService.cs
File metadata and controls
83 lines (66 loc) · 2.36 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
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Options;
using ImageMagick;
using IntelliTect.SyncUp.Data;
using SyncUp.Data.Models;
using System.Net;
using File = IntelliTect.Coalesce.Models.File;
namespace IntelliTect.SyncUp.Data.Services;
public class ImageService(AppDbContext db, IOptions<AzureBlobStorageOptions> options)
{
public async Task<Image> AddImage(string url)
{
byte[] bytes = [];
using (var client = new HttpClient())
{
bytes = await client.GetByteArrayAsync(url);
}
return await AddImage(new File(bytes));
}
public async Task<Image> AddImage(File file)
{
if (file.Length == 0 || file.Content is null) throw new Exception("No image provided");
try
{
var imageId = Guid.NewGuid().ToString().Replace("-", "");
var cloudBlob = GetBlobClient(imageId);
try
{
await cloudBlob.UploadAsync(file.Content, new BlobUploadOptions
{
Conditions = new() { IfNoneMatch = Azure.ETag.All }
});
}
catch (RequestFailedException ex)
{
throw new Exception("An Error occurred while trying to save the specified image to blob storage", ex);
}
// Reset stream position to 0 before reusing
file.Content.Position = 0;
var imageScan = new MagickImage(file.Content);
var colors = imageScan.Histogram();
string dominantColor = colors.MaxBy(kvp => kvp.Value).Key.ToHexString();
Image image = new()
{
ImageId = imageId,
Color = dominantColor
};
db.Images.Add(image);
await db.SaveChangesAsync();
return image;
}
catch (Exception ex)
{
throw new Exception("Unable to upload image", ex);
}
}
private BlobClient GetBlobClient(string relativeLocation)
{
var connectionString = options.Value.ConnectionString;
var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(options.Value.ImageContainerName);
return containerClient.GetBlobClient(relativeLocation);
}
}