public override async Task <GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request) { var response = new GetThumbnailResponse(); try { var apiKeyServiceClientCredentials = new ApiKeyServiceClientCredentials(request.EndPointKey1); var delegatingHandlers = new System.Net.Http.DelegatingHandler[] { }; IComputerVisionClient computerVision = new ComputerVisionClient( credentials: apiKeyServiceClientCredentials, handlers: delegatingHandlers) { Endpoint = request.EndPoint }; response.Thumbnail = await computerVision.GenerateThumbnailInStreamAsync( image : request.ImageStream, width : request.ThumbnailSize.Width, height : request.ThumbnailSize.Height, smartCropping : request.ThumbnailSize.SmartCropping); response.Success = true; } catch (Exception e) { response.FailureInformation = e.Message; } return(response); }
/// <summary> /// Uploads the image to Cognitive Services and generates a thumbnail. /// </summary> /// <param name="imageFilePath">The image file path.</param> /// <param name="width">Width of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param> /// <param name="height">Height of the thumbnail. It must be between 1 and 1024. Recommended minimum of 50.</param> /// <param name="smartCropping">Boolean flag for enabling smart cropping.</param> /// <returns>Awaitable stream containing the image thumbnail.</returns> private async Task <Stream> UploadAndThumbnailImageAsync(string imageFilePath, int width, int height, bool smartCropping) { // ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- // // Create Cognitive Services Vision API Service client. // using (var client = new ComputerVisionClient(Credentials) { Endpoint = Endpoint }) { Log("ComputerVisionClient is created"); using (Stream imageFileStream = File.OpenRead(imageFilePath)) { // // Upload an image and generate a thumbnail. // Log("Calling ComputerVisionClient.GenerateThumbnailInStreamAsync()..."); return(await client.GenerateThumbnailInStreamAsync(width, height, imageFileStream, smartCropping)); } } // ----------------------------------------------------------------------- // KEY SAMPLE CODE ENDS HERE // ----------------------------------------------------------------------- }
public async Task <(bool Success, string?Message)> Execute(Stream input, string blobName, string outputBlobName) { // Validate max width of the image using (Image image = Image.Load(input)) { if (image.Width > _settings.MaxMediaSize) { return(false, $"Image is too big. Requesting resize."); } } var blockBlob = Helpers.BlobHelper.GetBlobReference(outputBlobName) ?? throw new ArgumentException($"Blob '{blobName}' not found"); input.Position = 0; // Get smart thumbnail var credentials = new ApiKeyServiceClientCredentials(_settings.CognitiveServices.Key); using (var visionClient = new ComputerVisionClient(credentials) { Endpoint = _settings.CognitiveServices.Endpoint }) using (var result = await visionClient.GenerateThumbnailInStreamAsync(_settings.ThumbnailSize, _settings.ThumbnailSize, input, true)) using (var output = new MemoryStream()) { await result.CopyToAsync(output); output.Position = 0; await blockBlob.UploadFromStreamAsync(output); } return(true, null); }
public static async Task <Stream> SmartThumbnailGeneration(string fname, int width, int height, bool smartCropping) { Stream thumbnail = null; ComputerVisionClient client = Authenticate(API_key, API_location); if (File.Exists(fname)) { using (Stream stream = File.OpenRead(fname)) thumbnail = await client.GenerateThumbnailInStreamAsync(width, height, stream, smartCropping); } return(thumbnail); }
public async Task <string> GenerateThumbnailAsync(Stream image) { Stream thumbnail = await _client.GenerateThumbnailInStreamAsync(100, 100, image, smartCropping : true); byte[] thumbnailArray; using (var ms = new MemoryStream()) { thumbnail.CopyTo(ms); thumbnailArray = ms.ToArray(); } return(System.Convert.ToBase64String(thumbnailArray)); }
private async Task <string> GenerateThumbnailAsync(string imageUrl) { string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var thumbnailFile = Path.Combine(desktopPath, $@"image_{DateTime.Now.Ticks.ToString()}.jpg"); Stream stream = File.OpenRead(imageUrl); var imageStream = await visionClient.GenerateThumbnailInStreamAsync(200, 150, stream, smartCropping : true); FileStream fs = File.Create(thumbnailFile); imageStream.CopyTo(fs); fs.Flush(); fs.Close(); return(Path.GetFullPath(thumbnailFile)); }
private async Task <Stream> UploadAndThumbnailImage(string imageFilePath, int width, int height, bool smartCropping) { using (Stream imageFileStream = File.OpenRead(imageFilePath)) { // // Upload an image and generate a thumbnail // Log("Calling VisionServiceClient.GetThumbnailAsync()..."); return(await VisionServiceClient.GenerateThumbnailInStreamAsync(width, height, imageFileStream, smartCropping)); } // ----------------------------------------------------------------------- // KEY SAMPLE CODE ENDS HERE // ----------------------------------------------------------------------- }
private static async Task GetLocalThumbnailAsnc(ComputerVisionClient computerVision, string imagePath) { if (!File.Exists(imagePath)) { Console.WriteLine("\nInvalid image:\n{0} \n", imagePath); return; } using (Stream imageStream = File.OpenRead(imagePath)) { Stream thumbnail = await computerVision.GenerateThumbnailInStreamAsync(thumbnailWidth, thumbnailHeight, imageStream, false); string thumbnailFilePath = localImagePath.Insert(localImagePath.Length - 4, "_thumb"); SaveThumbnail(thumbnail, thumbnailFilePath); } }
private static async Task GetLocalThumbnailTask(ComputerVisionClient computerVisionClient, string imagePath, int Width, int Height, bool storeToDisk, string localImagePath) { if (!File.Exists(imagePath)) { return; } using (Stream stream = File.OpenRead(imagePath)) { Stream thumbnail = await computerVisionClient.GenerateThumbnailInStreamAsync( Width, Height, stream, true); string thumbnailFilePath = localImagePath.Insert(localImagePath.Length - 4, "_thumb"); Save(thumbnail, thumbnailFilePath, storeToDisk); } }
internal async Task <List <ImageAnalysis> > GetTagsForImages(List <string> filePaths) { List <VisualFeatureTypes> features = new List <VisualFeatureTypes>() { //VisualFeatureTypes.Categories, VisualFeatureTypes.Description, //VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType, //VisualFeatureTypes.Objects, VisualFeatureTypes.Tags }; ComputerVisionClient computerVision = new ComputerVisionClient( new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { }); computerVision.Endpoint = "https://northeurope.api.cognitive.microsoft.com"; List <ImageAnalysis> analysises = new List <ImageAnalysis>(); foreach (var item in filePaths) { string thumbnailFilePath = item.Insert(item.Length - 4, "_thumb"); using (Stream imageStream = File.OpenRead(item)) { Stream thumbnail = await computerVision.GenerateThumbnailInStreamAsync( thumbnailWidth, thumbnailHeight, imageStream, true); using (Stream file = File.Create(thumbnailFilePath)) { thumbnail.CopyTo(file); } } using (Stream imageStream = File.OpenRead(thumbnailFilePath)) { ImageAnalysis analysis = await computerVision.AnalyzeImageInStreamAsync( imageStream, features); analysises.Add(analysis); } } return(analysises); }
// Analyze a local image private static async Task GetThumbnailFromStreamAsync(ComputerVisionClient computerVision, string imagePath, int height, int width, string localSavePath) { if (!File.Exists(imagePath)) { Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath); return; } using (Stream imageStream = File.OpenRead(imagePath)) { Stream thumbnail = await computerVision.GenerateThumbnailInStreamAsync(width, height, imageStream, smartCropping : true); Console.WriteLine(imagePath); string imageName = Path.GetFileName(imagePath); string thumbnailFilePath = Path.Combine(localSavePath, imageName.Insert(imageName.Length - 4, "_thumb")); SaveThumbnail(thumbnail, thumbnailFilePath); } }
// Create a thumbnail from a local image private static async Task <bool> ResizeUpload( string fileName, byte[] sourceImage, int height, TextWriter log) { bool isResized = false; Image image = (Image)converter.ConvertFrom(sourceImage); using (var streamImage = new MemoryStream(sourceImage)) { if (image.Height > height) { var ratio = height / (float)image.Height; var _streamImage = await computerVision.GenerateThumbnailInStreamAsync((int)(image.Width *ratio), height, streamImage, true); await UploadStreamImageToStorage(fileName, _streamImage); isResized = true; } } return(isResized); }
/* * GENERATE THUMBNAIL * Taking in a URL and local image, this example will generate a thumbnail image with specified width/height (pixels). * The thumbnail will be saved locally. */ public static async Task GenerateThumbnail(ComputerVisionClient client, string urlImage, string localImage) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("GENERATE THUMBNAIL - URL & LOCAL IMAGE"); Console.WriteLine(); // Thumbnails will be saved locally in your bin\Debug\netcoreappx.x\ folder of this project. string localSavePath = @"."; // URL Console.WriteLine("Generating thumbnail with URL image..."); // Setting smartCropping to true enables the image to adjust its aspect ratio // to center on the area of interest in the image. Change the width/height, if desired. Stream thumbnailUrl = await client.GenerateThumbnailAsync(60, 60, urlImage, true); string imageNameUrl = Path.GetFileName(urlImage); string thumbnailFilePathUrl = Path.Combine(localSavePath, imageNameUrl.Insert(imageNameUrl.Length - 4, "_thumb")); Console.WriteLine("Saving thumbnail from URL image to " + thumbnailFilePathUrl); using (Stream file = File.Create(thumbnailFilePathUrl)) { thumbnailUrl.CopyTo(file); } Console.WriteLine(); // LOCAL Console.WriteLine("Generating thumbnail with local image..."); using (Stream imageStream = File.OpenRead(localImage)) { Stream thumbnailLocal = await client.GenerateThumbnailInStreamAsync(100, 100, imageStream, smartCropping : true); string imageNameLocal = Path.GetFileName(localImage); string thumbnailFilePathLocal = Path.Combine(localSavePath, imageNameLocal.Insert(imageNameLocal.Length - 4, "_thumb")); // Save to file Console.WriteLine("Saving thumbnail from local image to " + thumbnailFilePathLocal); using (Stream file = File.Create(thumbnailFilePathLocal)) { thumbnailLocal.CopyTo(file); } } Console.WriteLine(); }
// Create a thumbnail from a local image private static async Task GetLocalThumbnailAsnc( ComputerVisionClient computerVision, string imagePath) { if (!File.Exists(imagePath)) { Console.WriteLine( "\nUnable to open or read localImagePath:\n{0} \n", imagePath); return; } using (Stream imageStream = File.OpenRead(imagePath)) { Stream thumbnail = await computerVision.GenerateThumbnailInStreamAsync( thumbnailWidth, thumbnailHeight, imageStream, true); string thumbnailFilePath = localImagePath.Insert(localImagePath.Length - 4, "_thumb"); // Save the thumbnail to the same folder as the original image, // using the original name with the suffix "_thumb". SaveThumbnail(thumbnail, thumbnailFilePath); } }
public async Task <Stream> GenerateThumbnailAsync(FileStream fileStream) { return(await visionClient.GenerateThumbnailInStreamAsync(180, 180, fileStream, true)); }