public async Task InvokeAsync(HttpContext httpContext)
        {
            var responseStream = httpContext.Response.Body;
            var imageKey       = BuildBmpFileName(httpContext.Request.Path);
            //even if request doesn't contain image I'm still trying to grab the image from cache :(
            var cachedImage = _cache.Get(imageKey);

            if (cachedImage != null)
            {
                await cachedImage.CopyToAsync(responseStream);

                return;
            }

            using (var stream = new MemoryStream())
            {
                httpContext.Response.Body = stream;

                await _next(httpContext);

                var isValidImageType = httpContext.Response.ContentType?.Contains(ValidImageType) ?? false;
                if (isValidImageType)
                {
                    _cache.Add(stream, imageKey);
                }

                stream.Seek(0, SeekOrigin.Begin);
                await stream.CopyToAsync(responseStream);
            }
        }
Esempio n. 2
0
        public async Task <MemoryStream> RunAsync(string path)
        {
            MemoryStream memoryStream = new MemoryStream();

            using (Stream stream = await httpClient.GetStreamAsync(path))
            {
                await stream.CopyToAsync(memoryStream);
            }
            memoryStream.Position = 0;
            string checksum = ImageCacheUtils.GetChecksum(memoryStream);

            Rectangle[] faceRects = imageCache.Get(path.ToString(), checksum);

            if (faceRects == null)
            {
                faceRects = await faceDetection.Detect(path);

                if (faceRects == null)
                {
                    memoryStream.Position = 0;
                    return(memoryStream);
                }

                imageCache.Add(path.ToString(), checksum, faceRects);
            }

            if (faceRects.Length > 0)
            {
                memoryStream.Position = 0;
                Bitmap bitmap = new Bitmap(memoryStream);

                bitmap = imageEffect.Apply(bitmap, faceRects);

                memoryStream.Position = 0;
                bitmap.Save(memoryStream, ImageFormat.Png);
            }
            memoryStream.Position = 0;
            return(memoryStream);
        }