public HttpResponseMessage CategoryImage(int id, [FromUri] ImageParam param) { if (param == null) { throw new ArgumentNullException("param"); } HttpResponseMessage message = new HttpResponseMessage(); object[] args = new object[5]; args[0] = id; args[1] = param.h; args[2] = param.w; args[3] = param.Mode; bool?showDefault = param.ShowDefault; args[4] = showDefault.HasValue ? ((object)showDefault.GetValueOrDefault()) : ((object)1); string key = string.Format("categoryImage[id:{0}][w:{1}][h:{2}][m:{3}][d:{4}]", args); ImageCacheItem item = null; if ((item == null) || Settings.IsCacheDisabled) { Image categoryImage = ExcursionProvider.GetCategoryImage(id); if ((categoryImage == null) && (!(showDefault = param.ShowDefault).GetValueOrDefault() && showDefault.HasValue)) { message.StatusCode = HttpStatusCode.NotFound; } else { ImageFormatter formatter = new ImageFormatter(categoryImage, Pictures.nophoto) { Format = (categoryImage != null) ? ImageFormat.Jpeg : ImageFormat.Png }; param.ApplyFormat(formatter); Stream stream = formatter.CreateStream(); if (stream != null) { item = ImageCacheItem.Create(stream, formatter.MediaType); HttpContext.Current.Cache.Add(key, item, null, DateTime.Now.AddMinutes(10.0), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); message.Content = new StreamContent(stream); message.Content.Headers.ContentType = new MediaTypeHeaderValue(formatter.MediaType); message.Headers.CacheControl = new CacheControlHeaderValue(); message.Headers.CacheControl.Public = true; message.Headers.CacheControl.MaxAge = new TimeSpan?(TimeSpan.FromHours(1.0)); } else { message.StatusCode = HttpStatusCode.NotFound; } } } else { message.Content = new StreamContent(item.CraeteStream()); message.Content.Headers.ContentType = new MediaTypeHeaderValue(item.MediaType); } message.Headers.CacheControl = new CacheControlHeaderValue(); message.Headers.CacheControl.Public = true; message.Headers.CacheControl.MaxAge = new TimeSpan?(TimeSpan.FromHours(1.0)); return(message); }
// GET: api/PicturesExtracter/url public IHttpActionResult Get(string url) { //if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) // return BadRequest("Please enter valid URL!!!"); //else if (!url.Contains("http")) // return BadRequest("Please include \"Http\" URL!!!"); //else //{ string path = url; using (client = new WebClient()) { HtmlContent = client.DownloadString(url); } AllUrls = new List <string>(); var imageURLs = showMatch(HtmlContent, @"<(img)\b[^>]*>"); string[] split = imageURLs.Split(new Char[] { '"', '?' }); foreach (var item in split) { if (item.Contains(".jpg") || item.Contains(".png") || item.Contains(".svg")) { AllUrls.Add(item); } } //} ImageFormatter d = new ImageFormatter(); return(MM(AllUrls)); }
private static void testCrop() { Image i1 = ImageFileIO.ImageFromFile(@"C:\Users\chance\Documents\Visual Studio 2015\Capstone\HollisC_Collage\SimpleCollage\SimpleCollage\images\test2.bmp"); Image cropped = ImageFormatter.SquareImage(i1); ImageFileIO.saveImageToFile(cropped, @"C:\Users\chance\Documents\Visual Studio 2015\Capstone\HollisC_Collage\SimpleCollage\SimpleCollage\createdImages\test2.png"); }
public Image GetBaseImage() { Image img = ImageFileIO.ImageFromFile(ImageAddress); img = ImageFormatter.ScaleAndSquare(img, ImageSize); return(img); }
public CollageImage(string fileName, int size) { ImageSize = size; ImageAddress = fileName; ColorValues = new ColorValue(); Image img = ImageFileIO.ImageFromFile(fileName); Image scaled = ImageFormatter.ScaleAndSquare(img, size); img.Dispose(); CImage = scaled; GetAvgRGBFast(scaled); }
public override View GetView(int position, View convertView, ViewGroup parent) { var view = convertView ?? Activity.LayoutInflater.Inflate(Resource.Layout.grouplist_item, parent, false); var groupPhotoBitmap = ImageFormatter.GetBitmapFromUrl(Items[position].PhotoLink); view.FindViewById <RoundedImageView>(Resource.Id.groupPhoto).SetImageBitmap(groupPhotoBitmap); var groupName = TextFormatter.ShortenText(Items[position].Name, 28); view.FindViewById <TextView>(Resource.Id.groupName).Text = groupName; view.FindViewById <TextView>(Resource.Id.memberCount).Text = Items[position].Members.ToString(); return(view); }
public override View GetView(int position, View convertView, ViewGroup parent) { var view = convertView ?? Activity.LayoutInflater.Inflate(Resource.Layout.memberlist_item, parent, false); var checkBox = view.FindViewById <CheckBox>(Resource.Id.checkIn_checkbox); checkBox.SetOnCheckedChangeListener(null); var memberPhotoBitmap = ImageFormatter.GetBitmapFromUrl(FilteredItems[position].ThumbLink); view.FindViewById <RoundedImageView>(Resource.Id.thumblinkPhoto).SetImageBitmap(memberPhotoBitmap); view.FindViewById <TextView>(Resource.Id.memberName).Text = TextFormatter.ShortenText(FilteredItems[position].Name, 18); checkBox.Checked = FilteredItems[position].CheckedIn; checkBox.Tag = position; checkBox.SetOnCheckedChangeListener(this); return(view); }
/// <summary> /// Recieves an image, generates a table of average rgb values for each pixel /// </summary> /// <param name="template"></param> //public CollageTemplateImage(Image templateImage) //{ // TemplateImage = templateImage; // TemplateValues = new double[templateImage.Height, templateImage.Width]; // GenerateTemplateValues(); //} public CollageTemplateImage(Image template, ImageSize imageSize, CollageSize size = CollageSize.Medium) { int longSide = Math.Max(template.Height, template.Width); int maxPixels = (int)((double)size / (double)imageSize); double scaleby = ((double)maxPixels / (double)longSide); Image scaled = ImageFormatter.ScaleImage(template, scaleby, scaleby); //if (scaled.Height > MaxHeightWidth || scaled.Width > MaxHeightWidth) //{ // double scaleBy = Math.Max(scaled.Height, scaled.Width); // double newScale = MaxHeightWidth / scaleBy; // scaled = ImageFormatter.ScaleImage(scaled, newScale, newScale); //} TemplateImage = scaled; TemplateValues = new ColorValue[TemplateImage.Height, TemplateImage.Width]; GenerateTemplateValues(); }
public HttpResponseMessage Photo(int id, [FromUri] ImageParam param) { HttpResponseMessage message = new HttpResponseMessage(); ImageFormatter formatter = new ImageFormatter(GuideProvider.GetGuideImage(id), Pictures.GuideNoPhoto); param.ApplyFormat(formatter); Stream content = formatter.CreateStream(); if (content != null) { message.Content = new StreamContent(content); message.Content.Headers.ContentType = new MediaTypeHeaderValue(formatter.MediaType); return(message); } message.StatusCode = HttpStatusCode.NotFound; return(message); }
public void ApplyFormat(ImageFormatter formatter) { if (this.Width.HasValue) { formatter.Width = this.Width.Value; } if (this.Height.HasValue) { formatter.Height = this.Height.Value; } if (this.Mode == "fill") { formatter.Mode = ImageFormatter.AjustMode.fillRegion; } else if (this.Mode == "fit") { formatter.Mode = ImageFormatter.AjustMode.fitRegion; } else if (this.Mode == "original") { formatter.Mode = ImageFormatter.AjustMode.original; } }
public CollageImage(Image img, int size) { ColorValues = new ColorValue(); img = ImageFormatter.ScaleAndSquare(img, size); GetAvgRGBFast(img); }
/// <summary> /// Recieves an image, then calculates the average rgb for the image to create a collageImage object /// </summary> /// <param name="img"></param> public CollageImage(Image img) { ColorValues = new ColorValue(); img = ImageFormatter.SquareImage(img); GetAvgRGBFast(img); }
/// <summary> /// Returns empty string on success /// </summary> public virtual Asset ProcessPhoto(Asset asset) { return(base.ExecuteFunction("ProcessPhoto", delegate() { try { // get recent, just in case asset = this.API.Direct.Assets.GetById(asset.asset_id); if (asset == null || !asset.resize_required) { return null; // short circuit } asset.resize_attempts++; asset.resize_attempt_utc = DateTime.UtcNow; this.API.Direct.Assets.UpdateResizeAttemptInfo(asset.asset_id, asset.resize_attempts, asset.resize_attempt_utc.GetValueOrDefault(), "Attempting to resize"); System.Drawing.Image original = null; try { string raw_url = asset.raw_url; if (asset.type == AssetType.Video) { raw_url = asset.thumb_large_url; } original = this.GetImageFromUrl(raw_url); if (original == null) { return null; } int ix = raw_url.LastIndexOf('/'); string prefix = asset.raw_url.Substring(0, ix).Trim('/') + "/"; ix = prefix.ToLower().IndexOf(this.AmazonBucket.ToLower()); if (ix > -1) { prefix = prefix.Substring(ix + this.AmazonBucket.Length); } ix = prefix.ToLower().IndexOf(this.AmazonCloudFrontUrl.ToLower()); if (ix > -1) { prefix = prefix.Substring(ix + this.AmazonCloudFrontUrl.Length); } prefix = prefix.TrimStart('/'); string extension = Path.GetExtension(asset.raw_url); string imageCodecName = "jpeg"; EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); PixelFormat format = PixelFormat.Format24bppRgb; ResizeMode resizeMode = ResizeMode.Fill; if (!string.IsNullOrEmpty(asset.resize_mode)) { if (!Enum.TryParse <ResizeMode>(asset.resize_mode, true, out resizeMode)) { resizeMode = ResizeMode.Fill; // fallback } } if (resizeMode == ResizeMode.Fit) // we never want a backcolor { imageCodecName = "png"; extension = ".png"; format = PixelFormat.Format32bppArgb; } string cacheBuster = string.Format("{0}{1:HHmmss}", DateTime.UtcNow.DayOfYear, DateTime.UtcNow); string destinationSmall = prefix + cacheBuster + Path.GetFileNameWithoutExtension(asset.raw_url) + "_sm" + extension; string destinationMedium = prefix + cacheBuster + Path.GetFileNameWithoutExtension(asset.raw_url) + "_md" + extension; string destinationLarge = prefix + cacheBuster + Path.GetFileNameWithoutExtension(asset.raw_url) + "_lg" + extension; // create thumb Image smallImage = null; Image mediumImage = null; Image largeImage = null; try { Size dimensions = new Size(); if (TryParseDimensions(asset.thumb_small_dimensions, out dimensions)) { smallImage = ImageFormatter.Resize(original, resizeMode, (AnchorStyles.Middle | AnchorStyles.Center), dimensions.Width, dimensions.Height, format, InterpolationMode.HighQualityBicubic, Color.Transparent); } if (TryParseDimensions(asset.thumb_medium_dimensions, out dimensions)) { mediumImage = ImageFormatter.Resize(original, resizeMode, (AnchorStyles.Middle | AnchorStyles.Center), dimensions.Width, dimensions.Height, format, InterpolationMode.HighQualityBicubic, Color.Transparent); } if (TryParseDimensions(asset.thumb_large_dimensions, out dimensions)) { largeImage = ImageFormatter.Resize(original, resizeMode, (AnchorStyles.Middle | AnchorStyles.Center), dimensions.Width, dimensions.Height, format, InterpolationMode.HighQualityBicubic, Color.Transparent); } using (AmazonS3Client client = new AmazonS3Client(this.AmazonKeyID, this.AmazonSecret, RegionEndpoint.USEast1)) { // save small if (smallImage != null) { this.FlipImageIfNeeded(original, smallImage); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { smallImage.Save(memoryStream, GetCodecInfo(imageCodecName), encoderParameters); memoryStream.Position = 0; PutObjectRequest request = new PutObjectRequest() { BucketName = this.AmazonBucket, Key = destinationSmall, CannedACL = S3CannedACL.PublicRead, InputStream = memoryStream }; PutObjectResponse result = client.PutObject(request); if (result == null || (result.HttpStatusCode != HttpStatusCode.OK && result.HttpStatusCode != HttpStatusCode.Created)) { throw new Exception("Error saving to amazon"); } } } // save medium if (mediumImage != null) { this.FlipImageIfNeeded(original, mediumImage); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { mediumImage.Save(memoryStream, GetCodecInfo(imageCodecName), encoderParameters); memoryStream.Position = 0; PutObjectRequest request = new PutObjectRequest() { BucketName = this.AmazonBucket, Key = destinationMedium, CannedACL = S3CannedACL.PublicRead, InputStream = memoryStream }; PutObjectResponse result = client.PutObject(request); if (result == null || (result.HttpStatusCode != HttpStatusCode.OK && result.HttpStatusCode != HttpStatusCode.Created)) { throw new Exception("Error saving to amazon"); } } } // save large if (largeImage != null) { this.FlipImageIfNeeded(original, largeImage); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { largeImage.Save(memoryStream, GetCodecInfo(imageCodecName), encoderParameters); memoryStream.Position = 0; PutObjectRequest request = new PutObjectRequest() { BucketName = this.AmazonBucket, Key = destinationLarge, CannedACL = S3CannedACL.PublicRead, InputStream = memoryStream }; PutObjectResponse result = client.PutObject(request); if (result == null || (result.HttpStatusCode != HttpStatusCode.OK && result.HttpStatusCode != HttpStatusCode.Created)) { throw new Exception("Error saving to amazon"); } } } asset = this.API.Direct.Assets.GetById(asset.asset_id); // get recent if (asset != null) { if (smallImage != null) { asset.thumb_small_url = AmazonUtility.ConstructAmazonUrl(this.AmazonCloudFrontUrl, this.AmazonPublicUrl, this.AmazonBucket, destinationSmall); asset.thumb_small_dimensions = string.Format("{0}x{1}", smallImage.Width, smallImage.Height); } if (mediumImage != null) { asset.thumb_medium_url = AmazonUtility.ConstructAmazonUrl(this.AmazonCloudFrontUrl, this.AmazonPublicUrl, this.AmazonBucket, destinationMedium); asset.thumb_medium_dimensions = string.Format("{0}x{1}", mediumImage.Width, mediumImage.Height); } if (largeImage != null) { asset.thumb_large_url = AmazonUtility.ConstructAmazonUrl(this.AmazonCloudFrontUrl, this.AmazonPublicUrl, this.AmazonBucket, destinationLarge); asset.thumb_large_dimensions = string.Format("{0}x{1}", largeImage.Width, largeImage.Height); } asset.available = true; asset.resize_processing = false; asset.resize_required = false; asset.resize_status = EncoderStatus.complete.ToString(); asset.resize_log += "Resize Completed Processing on " + DateTime.UtcNow.ToString(); this.API.Direct.Assets.Update(asset); HealthReporter.Current.UpdateMetric(HealthTrackType.Each, HealthReporter.PHOTO_RESIZE_SUCCESS, 0, 1); } else { HealthReporter.Current.UpdateMetric(HealthTrackType.Each, HealthReporter.PHOTO_RESIZE_FAILED, 0, 1); } return asset; } } finally { if (smallImage != null) { smallImage.Dispose(); } if (mediumImage != null) { mediumImage.Dispose(); } if (largeImage != null) { largeImage.Dispose(); } } } finally { if (original != null) { original.Dispose(); } } } catch (Exception ex) { this.API.Direct.Assets.UpdateResizeInfo(asset.asset_id, false, EncoderStatus.not_processed.ToString(), CoreUtility.FormatException(ex)); HealthReporter.Current.UpdateMetric(HealthTrackType.Each, HealthReporter.PHOTO_RESIZE_FAILED, 0, 1); this.IFoundation.LogError(ex, "PerformProcessPhoto"); return null; } })); }