forked from TomDudfield/AutoAltTags
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDescribeImage.cs
More file actions
62 lines (51 loc) · 2.06 KB
/
DescribeImage.cs
File metadata and controls
62 lines (51 loc) · 2.06 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
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Microsoft.ProjectOxford.Vision;
namespace AutoAltTags
{
class DescribeImage
{
private readonly string _apiKey;
public DescribeImage(string apiKey, string defaultApiRoot)
{
_apiKey = apiKey;
_defaultApiRoot = defaultApiRoot;
}
public string GetDescription(Stream stream)
{
string description = string.Empty;
using (Image oldImage = Image.FromStream(stream))
{
Size newSize = CalculateDimensions(oldImage.Size, 2048);
using (Bitmap bitmap = new Bitmap(oldImage, newSize))
{
MemoryStream outputStream = new MemoryStream();
bitmap.Save(outputStream, ImageFormat.Jpeg);
outputStream.Position = 0;
VisionServiceClient visionServiceClient = new VisionServiceClient(_apiKey, _defaultApiRoot);
var analysisResult = visionServiceClient.DescribeAsync(outputStream);
if (analysisResult.Result.Description.Captions != null && analysisResult.Result.Description.Captions.Any())
description = analysisResult.Result.Description.Captions.First().Text;
return description;
}
}
}
private static Size CalculateDimensions(Size oldSize, int maxSize)
{
Size newSize = new Size(oldSize.Width, oldSize.Height);
if (oldSize.Height > oldSize.Width && oldSize.Height > maxSize)
{
newSize.Width = (int)(oldSize.Width * ((float)maxSize / oldSize.Height));
newSize.Height = maxSize;
}
else if (oldSize.Height > oldSize.Width && oldSize.Width > maxSize)
{
newSize.Width = maxSize;
newSize.Height = (int)(oldSize.Height * ((float)maxSize / oldSize.Width));
}
return newSize;
}
}
}