コード例 #1
0
        private static async Task ProcessDirectoryAsync(string dir, bool forceUpdate = false)
        {
            Console.WriteLine($"Processing Directory {dir}");
            var imageExtensions = new HashSet <string>(StringComparer.OrdinalIgnoreCase)
            {
                ".png",
                ".jpg",
                ".bmp",
                ".jpeg",
                ".gif"
            };

            foreach (var file in
                     from file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
                     where imageExtensions.Contains(Path.GetExtension(file))
                     select file)
            {
                try
                {
                    var fileName = Path.GetFileName(file);
                    var existing = await documentDb.FindDocumentByIdAsync <ImageMetadata>(fileName);

                    if (existing == null || forceUpdate)
                    {
                        Console.WriteLine($"Processing {file}");
                        // Resize (if needed) in order to reduce network latency and errors due to large files. Then store the result in a temporary file.
                        var resized = Util.ResizeIfRequired(file, 750);
                        Func <Task <Stream> > imageCB  = async() => File.OpenRead(resized.Item2);
                        ImageInsights         insights = await ImageProcessor.ProcessImageAsync(imageCB, fileName);

                        Util.AdjustFaceInsightsBasedOnResizing(insights, resized.Item1);
                        Console.WriteLine($"Insights: {JsonConvert.SerializeObject(insights, Formatting.None)}");
                        var imageBlob = await blobStorage.UploadImageAsync(imageCB, fileName);

                        var metadata = new ImageMetadata(file);
                        metadata.AddInsights(insights);
                        metadata.BlobUri = imageBlob.Uri;
                        if (existing == null)
                        {
                            metadata = (await documentDb.CreateDocumentIfNotExistsAsync(metadata, metadata.Id)).Item2;
                        }
                        else
                        {
                            metadata = await documentDb.UpdateDocumentAsync(metadata, metadata.Id);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Skipping {file}, exists and 'forceUpdate' not set.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error: {e}");
                }
            }
        }