/// <summary> /// Gets the ImageProcessor Url from the image path. /// </summary> /// <param name="imageUrl"> /// The image url. /// </param> /// <param name="width"> /// The width of the output image. /// </param> /// <param name="height"> /// The height of the output image. /// </param> /// <param name="imageCropperValue"> /// The Json data from the Umbraco Core Image Cropper property editor /// </param> /// <param name="cropAlias"> /// The crop alias. /// </param> /// <param name="quality"> /// Quality percentage of the output image. /// </param> /// <param name="imageCropMode"> /// The image crop mode. /// </param> /// <param name="imageCropAnchor"> /// The image crop anchor. /// </param> /// <param name="preferFocalPoint"> /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one /// </param> /// <param name="useCropDimensions"> /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters /// </param> /// <param name="cacheBusterValue"> /// Add a serialised date of the last edit of the item to ensure client cache refresh when updated /// </param> /// <param name="furtherOptions"> /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example: /// <example> /// <![CDATA[ /// furtherOptions: "&bgcolor=fff" /// ]]> /// </example> /// </param> /// <param name="ratioMode"> /// Use a dimension as a ratio /// </param> /// <param name="upScale"> /// If the image should be upscaled to requested dimensions /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string GetCropUrl( this string imageUrl, int?width = null, int?height = null, string imageCropperValue = null, string cropAlias = null, int?quality = null, ImageCropMode?imageCropMode = null, ImageCropAnchor?imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode?ratioMode = null, bool upScale = true) { if (string.IsNullOrEmpty(imageUrl)) { return(string.Empty); } ImageCropDataSet cropDataSet = null; if (string.IsNullOrEmpty(imageCropperValue) == false && imageCropperValue.DetectIsJson() && (imageCropMode == ImageCropMode.Crop || imageCropMode == null)) { cropDataSet = imageCropperValue.SerializeToCropDataSet(); } return(GetCropUrl( imageUrl, cropDataSet, width, height, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale)); }
public static IHtmlString GetCropCdnUrl(this UrlHelper urlHelper, ImageCropDataSet imageCropper, int?width = null, int?height = null, string propertyAlias = global::Umbraco.Core.Constants.Conventions.Media.File, string cropAlias = null, int?quality = null, ImageCropMode?imageCropMode = null, ImageCropAnchor?imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode?ratioMode = null, bool upScale = true, bool htmlEncode = true ) { // if no cacheBusterValue provided we need to make one if (cacheBusterValue == null) { cacheBusterValue = DateTime.UtcNow.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture); } var cropUrl = GetCropUrl(imageCropper.Src, imageCropper, width, height, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale); return(UrlToCdnUrl(cropUrl, htmlEncode)); }
internal static string GetCropBaseUrl(this ImageCropDataSet cropDataSet, string cropAlias, bool preferFocalPoint) { var cropUrl = new StringBuilder(); var crop = cropDataSet.GetCrop(cropAlias); // if crop alias has been specified but not found in the Json we should return null if (string.IsNullOrEmpty(cropAlias) == false && crop == null) { return(null); } if ((preferFocalPoint && cropDataSet.HasFocalPoint()) || (crop != null && crop.Coordinates == null && cropDataSet.HasFocalPoint()) || (string.IsNullOrEmpty(cropAlias) && cropDataSet.HasFocalPoint())) { cropUrl.Append("?center=" + cropDataSet.FocalPoint.Top.ToString(CultureInfo.InvariantCulture) + "," + cropDataSet.FocalPoint.Left.ToString(CultureInfo.InvariantCulture)); cropUrl.Append("&mode=crop"); } else if (crop != null && crop.Coordinates != null && preferFocalPoint == false) { cropUrl.Append("?crop="); cropUrl.Append(crop.Coordinates.X1.ToString(CultureInfo.InvariantCulture)).Append(","); cropUrl.Append(crop.Coordinates.Y1.ToString(CultureInfo.InvariantCulture)).Append(","); cropUrl.Append(crop.Coordinates.X2.ToString(CultureInfo.InvariantCulture)).Append(","); cropUrl.Append(crop.Coordinates.Y2.ToString(CultureInfo.InvariantCulture)); cropUrl.Append("&cropmode=percentage"); } else { cropUrl.Append("?anchor=center"); cropUrl.Append("&mode=crop"); } return(cropUrl.ToString()); }
internal static ImageCropData GetCrop(this ImageCropDataSet dataset, string cropAlias) { if (dataset == null || dataset.Crops == null || !dataset.Crops.Any()) { return(null); } return(dataset.Crops.GetCrop(cropAlias)); }
public void Init() { // JSON test data taken from Umbraco unit-test: // https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs var json = "{\"focalPoint\": {\"left\": 0.96,\"top\": 0.80827067669172936},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; Value = JsonConvert.DeserializeObject <ImageCropDataSet>(json); Content = new MockPublishedContent { Properties = new[] { new MockPublishedContentProperty("myProperty", Value) } }; }
/// <summary> /// Gets the url for the given node. /// </summary> /// <param name="content">The cached content.</param> /// <returns>The <see cref="string"/></returns> private string GetUrl(IPublishedContent content) { if (content.HasProperty(Constants.Conventions.Media.File)) { ImageCropDataSet crops = content.GetPropertyValue <ImageCropDataSet>(Constants.Conventions.Media.File); if (crops != null) { return(crops.Src); } } return(content.Url); }
/// <summary> /// Gets the url for the given node. /// </summary> /// <param name="node"></param> /// <returns></returns> private string GetUrl(IPublishedContent node) { if (node.HasProperty("umbracoFile")) { ImageCropDataSet crops = node.GetPropertyValue <ImageCropDataSet>("umbracoFile"); if (crops != null) { return(crops.Src); } } return(node.Url); }
public static string GetResponsiveCropUrl( this ImageCropDataSet cropDataSet, int width, int height ) { return(cropDataSet.GetCropUrl( width, height, quality: 90, ratioMode: ImageCropRatioMode.Height, furtherOptions: "&slimmage=true" )); }
internal static ImageCropDataSet SerializeToCropDataSet(this string json) { var imageCrops = new ImageCropDataSet(); if (json.DetectIsJson()) { try { imageCrops = JsonConvert.DeserializeObject<ImageCropDataSet>(json); } catch (Exception ex) { LogHelper.Error(typeof(ImageCropperBaseExtensions), "Could not parse the json string: " + json, ex); } } return imageCrops; }
internal static ImageCropDataSet SerializeToCropDataSet(this string json) { var imageCrops = new ImageCropDataSet(); if (json.DetectIsJson()) { try { imageCrops = JsonConvert.DeserializeObject <ImageCropDataSet>(json); } catch (Exception ex) { LogHelper.Error(typeof(CropHealer), "Could not parse the json string: " + json, ex); } } return(imageCrops); }
private static List <IEnterspeedProperty> GetCropsProperty(ImageCropDataSet value) { var crops = new List <IEnterspeedProperty>(); if (value != null && value.Crops != null) { foreach (var crop in value.Crops) { var cropProperties = new Dictionary <string, IEnterspeedProperty> { { "alias", new StringEnterspeedProperty(crop.Alias) }, { "height", new NumberEnterspeedProperty(crop.Height) }, { "width", new NumberEnterspeedProperty(crop.Width) } }; ObjectEnterspeedProperty cropCoordinatesProperty = null; if (crop.Coordinates != null) { var cropCoordinatesProperties = new Dictionary <string, IEnterspeedProperty> { { "X1", new NumberEnterspeedProperty(double.Parse(crop.Coordinates.X1.ToString(CultureInfo.InvariantCulture))) }, { "Y1", new NumberEnterspeedProperty(double.Parse(crop.Coordinates.Y1.ToString(CultureInfo.InvariantCulture))) }, { "X2", new NumberEnterspeedProperty(double.Parse(crop.Coordinates.X2.ToString(CultureInfo.InvariantCulture))) }, { "Y2", new NumberEnterspeedProperty(double.Parse(crop.Coordinates.Y2.ToString(CultureInfo.InvariantCulture))) } }; cropCoordinatesProperty = new ObjectEnterspeedProperty(cropCoordinatesProperties); } cropProperties.Add("coordinates", cropCoordinatesProperty); crops.Add(new ObjectEnterspeedProperty(cropProperties)); } } return(crops); }
/// <summary> /// Initialises the instance from the db value /// </summary> public void Initialise(string dbValue) { if (!string.IsNullOrWhiteSpace(dbValue)) { JsonConvert.PopulateObject(dbValue, this); _underlying = JsonConvert.DeserializeObject <ImageCropDataSet>(dbValue); //This is useful as it has logic for generating the crop URLs Effects.SetUnderlyingDataset(_underlying); if (Crops == null) { Crops = new List <ImageCrop>(); } Crops.ForEach(x => x.SetUnderlyingDataset(_underlying)); var crops = GetCropsFromProperties(); foreach (var crop in crops) { crop.Key.SetValue(this, Crops.FirstOrDefault(x => x.Alias == crop.Value.Alias)); } } }
private static ObjectEnterspeedProperty GetFocalPoint(ImageCropDataSet value) { if (value == null || value.FocalPoint == null) { return(null); } var focalPointProperties = new Dictionary <string, IEnterspeedProperty> { { "left", new NumberEnterspeedProperty( double.Parse(value.FocalPoint.Left.ToString(CultureInfo.InvariantCulture))) }, { "top", new NumberEnterspeedProperty( double.Parse(value.FocalPoint.Top.ToString(CultureInfo.InvariantCulture))) } }; return(new ObjectEnterspeedProperty(focalPointProperties)); }
internal static ImageCropDataSet DeserializeToCropDataSet(this string json) { var imageCrops = new ImageCropDataSet(); if (json.DetectIsJson()) { try { imageCrops = JsonConvert.DeserializeObject <ImageCropDataSet>(json, new JsonSerializerSettings { Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal }); } catch (Exception ex) { LogHelper.Error(typeof(ImageCropperBaseExtensions), "Could not parse the json string: " + json, ex); } } return(imageCrops); }
public void SetUnderlyingDataset(ImageCropDataSet underlying) { _underlying = underlying; Effects.SetUnderlyingDataset(_underlying, Alias); }
/// <summary> /// Gets the ImageProcessor Url from the image path. /// </summary> /// <param name="imageUrl"> /// The image url. /// </param> /// <param name="cropDataSet"></param> /// <param name="width"> /// The width of the output image. /// </param> /// <param name="height"> /// The height of the output image. /// </param> /// <param name="cropAlias"> /// The crop alias. /// </param> /// <param name="quality"> /// Quality percentage of the output image. /// </param> /// <param name="imageCropMode"> /// The image crop mode. /// </param> /// <param name="imageCropAnchor"> /// The image crop anchor. /// </param> /// <param name="preferFocalPoint"> /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one /// </param> /// <param name="useCropDimensions"> /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters /// </param> /// <param name="cacheBusterValue"> /// Add a serialised date of the last edit of the item to ensure client cache refresh when updated /// </param> /// <param name="furtherOptions"> /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example: /// <example> /// <![CDATA[ /// furtherOptions: "&bgcolor=fff" /// ]]> /// </example> /// </param> /// <param name="ratioMode"> /// Use a dimension as a ratio /// </param> /// <param name="upScale"> /// If the image should be upscaled to requested dimensions /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string GetCropUrl( this string imageUrl, ImageCropDataSet cropDataSet, int?width = null, int?height = null, string cropAlias = null, int?quality = null, ImageCropMode?imageCropMode = null, ImageCropAnchor?imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode?ratioMode = null, bool upScale = true) { if (string.IsNullOrEmpty(imageUrl) == false) { var imageProcessorUrl = new StringBuilder(); if (cropDataSet != null && (imageCropMode == ImageCropMode.Crop || imageCropMode == null)) { var crop = cropDataSet.GetCrop(cropAlias); imageProcessorUrl.Append(cropDataSet.Src); var cropBaseUrl = cropDataSet.GetCropBaseUrl(cropAlias, preferFocalPoint); if (cropBaseUrl != null) { imageProcessorUrl.Append(cropBaseUrl); } else { return(null); } if (crop != null & useCropDimensions) { width = crop.Width; height = crop.Height; } // If a predefined crop has been specified & there are no coordinates & no ratio mode, but a width parameter has been passed we can get the crop ratio for the height if (crop != null && string.IsNullOrEmpty(cropAlias) == false && crop.Coordinates == null && ratioMode == null && width != null && height == null) { var heightRatio = (decimal)crop.Height / (decimal)crop.Width; imageProcessorUrl.Append("&heightratio=" + heightRatio.ToString(CultureInfo.InvariantCulture)); } // If a predefined crop has been specified & there are no coordinates & no ratio mode, but a height parameter has been passed we can get the crop ratio for the width if (crop != null && string.IsNullOrEmpty(cropAlias) == false && crop.Coordinates == null && ratioMode == null && width == null && height != null) { var widthRatio = (decimal)crop.Width / (decimal)crop.Height; imageProcessorUrl.Append("&widthratio=" + widthRatio.ToString(CultureInfo.InvariantCulture)); } } else { imageProcessorUrl.Append(imageUrl); if (imageCropMode == null) { imageCropMode = ImageCropMode.Pad; } imageProcessorUrl.Append("?mode=" + imageCropMode.ToString().ToLower()); if (imageCropAnchor != null) { imageProcessorUrl.Append("&anchor=" + imageCropAnchor.ToString().ToLower()); } } var hasFormat = furtherOptions != null && furtherOptions.InvariantContains("&format="); //Only put quality here, if we don't have a format specified. //Otherwise we need to put quality at the end to avoid it being overridden by the format. if (quality != null && hasFormat == false) { imageProcessorUrl.Append("&quality=" + quality); } if (width != null && ratioMode != ImageCropRatioMode.Width) { imageProcessorUrl.Append("&width=" + width); } if (height != null && ratioMode != ImageCropRatioMode.Height) { imageProcessorUrl.Append("&height=" + height); } if (ratioMode == ImageCropRatioMode.Width && height != null) { // if only height specified then assume a sqaure if (width == null) { width = height; } var widthRatio = (decimal)width / (decimal)height; imageProcessorUrl.Append("&widthratio=" + widthRatio.ToString(CultureInfo.InvariantCulture)); } if (ratioMode == ImageCropRatioMode.Height && width != null) { // if only width specified then assume a sqaure if (height == null) { height = width; } var heightRatio = (decimal)height / (decimal)width; imageProcessorUrl.Append("&heightratio=" + heightRatio.ToString(CultureInfo.InvariantCulture)); } if (upScale == false) { imageProcessorUrl.Append("&upscale=false"); } if (furtherOptions != null) { imageProcessorUrl.Append(furtherOptions); } //If furtherOptions contains a format, we need to put the quality after the format. if (quality != null && hasFormat) { imageProcessorUrl.Append("&quality=" + quality); } if (cacheBusterValue != null) { imageProcessorUrl.Append("&rnd=").Append(cacheBusterValue); } return(imageProcessorUrl.ToString()); } return(string.Empty); }
public void SetUnderlyingDataset(ImageCropDataSet underlying, string alias = null) { _underlying = underlying; _isOriginal = alias == null; _alias = alias; }
public static string GetCropUrl( this ImageCropDataSet cropDataSet, int?width = null, int?height = null, string cropAlias = null, int?quality = null, ImageCropMode?imageCropMode = null, ImageCropAnchor?imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode?ratioMode = null, bool upScale = true ) { var imageResizerUrl = new StringBuilder(); imageResizerUrl.Append(cropDataSet.Src); if (imageCropMode == ImageCropMode.Crop || imageCropMode == null) { var crop = cropDataSet.GetCrop(cropAlias); var cropBaseUrl = cropDataSet.GetCropBaseUrl(cropAlias, preferFocalPoint); if (cropBaseUrl != null) { imageResizerUrl.Append(cropBaseUrl); } else { return(null); } if (crop != null & useCropDimensions) { width = crop.Width; height = crop.Height; } } else { imageResizerUrl.Append("?mode=" + imageCropMode.ToString().ToLower()); if (imageCropAnchor != null) { imageResizerUrl.Append("&anchor=" + imageCropAnchor.ToString().ToLower()); } } if (quality != null) { imageResizerUrl.Append("&quality=" + quality); } if (width != null && ratioMode != ImageCropRatioMode.Width) { imageResizerUrl.Append("&width=" + width); } if (height != null && ratioMode != ImageCropRatioMode.Height) { imageResizerUrl.Append("&height=" + height); } if (ratioMode == ImageCropRatioMode.Width && height != null) { //if only height specified then assume a sqaure if (width == null) { width = height; } var widthRatio = (decimal)width / (decimal)height; imageResizerUrl.Append("&widthratio=" + widthRatio.ToString(CultureInfo.InvariantCulture)); } if (ratioMode == ImageCropRatioMode.Height && width != null) { //if only width specified then assume a sqaure if (height == null) { height = width; } var heightRatio = (decimal)height / (decimal)width; imageResizerUrl.Append("&heightratio=" + heightRatio.ToString(CultureInfo.InvariantCulture)); } if (upScale == false) { imageResizerUrl.Append("&upscale=false"); } if (furtherOptions != null) { imageResizerUrl.Append(furtherOptions); } if (cacheBusterValue != null) { imageResizerUrl.Append("&rnd=").Append(cacheBusterValue); } return(imageResizerUrl.ToString()); }
/// <summary> /// Initialises the instance from the db value /// </summary> public void Initialise(string dbValue) { if (!string.IsNullOrWhiteSpace(dbValue)) { JsonConvert.PopulateObject(dbValue, this); _underlying = JsonConvert.DeserializeObject<ImageCropDataSet>(dbValue); //This is useful as it has logic for generating the crop URLs Effects.SetUnderlyingDataset(_underlying); if (Crops == null) { Crops = new List<ImageCrop>(); } Crops.ForEach(x => x.SetUnderlyingDataset(_underlying)); var crops = GetCropsFromProperties(); foreach (var crop in crops) { crop.Key.SetValue(this, Crops.FirstOrDefault(x => x.Alias == crop.Value.Alias)); } } }
public ActionResult MarketingActualSubmit(MarketingActual marketingActual) { if (!ModelState.IsValid || marketingActual == null) return CurrentUmbracoPage(); var company = Company(); var contentService = Services.ContentService; IContent ma = null; if (!marketingActual.ID.HasValue) { var maParent = umbracoHelper.TypedContentAtRoot().First().FirstChild(x => x.ContentType.Alias.Equals("dtNewsList")); ma = contentService.CreateContent(marketingActual.Name, maParent.Id, "dtNews", Members.GetCurrentMemberId()); } else ma = contentService.GetById(marketingActual.ID.Value); ma.Name = marketingActual.Name; ma.SetValue("nCompanyNodeId", company.Id); ma.SetValue("nDescription", marketingActual.Description); ma.SetValue("nContent", marketingActual.Content); if (marketingActual.NewThumbnail != null && marketingActual.NewThumbnail.InputStream != null) { var filename = JobsplusHelpers.RemoveDiacritics(Path.GetFileName(marketingActual.NewThumbnail.FileName)); var path = "/media/" + ma.Id.ToString() + "/"; var fullPath = Server.MapPath("~" + path); var dir = new DirectoryInfo(fullPath); if (!dir.Exists) dir.Create(); try { marketingActual.NewThumbnail.SaveAs(fullPath + filename); } catch (Exception ex) { ModelState.AddModelError("", "Při nahrávání náhledového obrázku došlo k chybě:"); TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex)); return CurrentUmbracoPage(); } var filepath = path + filename; Image img = null; try { img = Image.FromFile(fullPath + filename); } catch (Exception ex) { ModelState.AddModelError("", "Nahrávaný soubor náhledového obrázku nemá správný formát:"); System.IO.File.Delete(fullPath + filename); TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex)); return CurrentUmbracoPage(); } var newThumbnail = new ImageCropDataSet(); newThumbnail.FocalPoint.Left = new decimal(0.5); newThumbnail.FocalPoint.Top = new decimal(0.5); newThumbnail.Src = filepath; ma.SetValue("nThumbnail", newThumbnail); } contentService.Save(ma); if (marketingActual.IsPublished) contentService.Publish(ma); else contentService.UnPublish(ma); return Redirect("/firma/marketingove-aktuality/"); }
internal static string ImageCropDataSetRepair(this ImageCropDataSet cropDataSet, string json, int sourceWidthPx, int sourceHeightPx, List <ImageCropData> imageCrops = null) { var healedSomething = false; if (cropDataSet.Src == null) { // convert from image path to cropper cropDataSet.Src = json; healedSomething = true; } if (cropDataSet.FocalPoint == null) { cropDataSet.FocalPoint = new ImageCropFocalPoint() { Left = 0.5m, Top = 0.5m }; healedSomething = true; } if (imageCrops != null && imageCrops.Any()) { var currentCrops = new List <ImageCropData>(); if (cropDataSet.Crops != null) { currentCrops = cropDataSet.Crops.ToList(); // delete crops that have been removed from the data type foreach (var crop in cropDataSet.Crops) { if (!imageCrops.Select(x => x.Alias).Contains(crop.Alias)) { currentCrops.Remove(crop); healedSomething = true; } } } foreach (var cropDef in imageCrops) { var cropDefInCurrent = currentCrops.FirstOrDefault(x => x.Alias == cropDef.Alias); // check if width or height different if (cropDefInCurrent != null && (cropDef.Width != cropDefInCurrent.Width || cropDef.Height != cropDefInCurrent.Height)) { var index = currentCrops.IndexOf(cropDefInCurrent); // see if we can calculate new coordinates if (cropDefInCurrent.Coordinates != null && sourceHeightPx > 0 && sourceWidthPx > 0) { // crop height changed if (cropDef.Height != cropDefInCurrent.Height) { // try to extend down first var heightChange = cropDef.Height - cropDefInCurrent.Height; var heightChangePercentage = Math.Round((decimal)heightChange / sourceHeightPx, 17); // check we are not going to hit the bottom else extend up if ((cropDefInCurrent.Coordinates.Y2 - heightChangePercentage) >= 0) { cropDefInCurrent.Coordinates.Y2 = cropDefInCurrent.Coordinates.Y2 - heightChangePercentage; } else if ((cropDefInCurrent.Coordinates.Y1 - heightChangePercentage) >= 0) { cropDefInCurrent.Coordinates.Y1 = cropDefInCurrent.Coordinates.Y1 - heightChangePercentage; } else { // if it's too big to grow, clear the coords cropDefInCurrent.Coordinates = null; } } // crop width changed if (cropDefInCurrent.Coordinates != null && cropDef.Width != cropDefInCurrent.Width) { // try to extend to the right first var widthChange = cropDef.Width - cropDefInCurrent.Width; var widthChangePercentage = Math.Round((decimal)widthChange / sourceWidthPx, 17); // check we are not going to hit the right else extend to the left if ((cropDefInCurrent.Coordinates.X2 - widthChangePercentage) >= 0) { cropDefInCurrent.Coordinates.X2 = cropDefInCurrent.Coordinates.X2 - widthChangePercentage; } else if ((cropDefInCurrent.Coordinates.X1 - widthChangePercentage) >= 0) { cropDefInCurrent.Coordinates.X1 = cropDefInCurrent.Coordinates.X1 - widthChangePercentage; } else { // if it's too big to grow, clear the coords cropDefInCurrent.Coordinates = null; } } } cropDefInCurrent.Width = cropDef.Width; cropDefInCurrent.Height = cropDef.Height; currentCrops.RemoveAt(index); currentCrops.Insert(index, cropDefInCurrent); healedSomething = true; } if (!currentCrops.Select(x => x.Alias).Contains(cropDef.Alias)) { currentCrops.Add(cropDef); healedSomething = true; } } if (cropDataSet.Crops == null) { cropDataSet.Crops = new List <ImageCropData>(); healedSomething = true; } cropDataSet.Crops = currentCrops; } if (healedSomething) { return (JsonConvert.SerializeObject( cropDataSet, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) .Replace(":0.0,", ":0,") .Replace(":0.0}", ":0}")); } return(null); }
private void InitPublishedProperties() { if (!PublishedCachesResolver.HasCurrent) { var mockPublishedContentCache = new Mock <IPublishedContentCache>(); mockPublishedContentCache .Setup(x => x.GetById(It.IsAny <UmbracoContext>(), It.IsAny <bool>(), It.IsAny <int>())) .Returns <UmbracoContext, bool, int>((ctx, preview, id) => new MockPublishedContent { Id = id }); mockPublishedContentCache .Setup(x => x.GetByXPath(It.IsAny <UmbracoContext>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <XPathVariable[]>())) .Returns <UmbracoContext, bool, string, XPathVariable[]>( (ctx, preview, xpath, vars) => { switch (xpath) { case "/root": case "id(1111)": return(new MockPublishedContent { Id = 1111 }.AsEnumerableOfOne()); case "id(2222)": return(new MockPublishedContent { Id = 2222 }.AsEnumerableOfOne()); case "id(3333)": return(new MockPublishedContent { Id = 3333 }.AsEnumerableOfOne()); default: return(Enumerable.Empty <IPublishedContent>()); } }); PublishedCachesResolver.Current = new PublishedCachesResolver(new PublishedCaches(mockPublishedContentCache.Object, new Mock <IPublishedMediaCache>().Object)); // JSON test data taken from Umbraco unit-test: // https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs string json = "{\"focalPoint\": {\"left\": 0.96,\"top\": 0.80827067669172936},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; this.dataSet = JsonConvert.DeserializeObject <ImageCropDataSet>(json); this.link = new RelatedLink { Caption = "Test Caption", Content = null, Id = 98765, IsDeleted = true, IsInternal = true, Link = "test link", NewWindow = true }; if (!Resolution.IsFrozen) { Resolution.Freeze(); } } }
public IHttpActionResult RotateMedia(RotateInstruction rotateInstruction) { var mediaId = rotateInstruction.MediaId; var turns = rotateInstruction.Turns; var mediaService = Services.MediaService; var mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider <MediaFileSystem>(); var isCropper = false; var imageCrops = new ImageCropDataSet(); // get mediaItem var mediaItem = mediaService.GetById(mediaId); var mediaItemAlias = mediaItem.ContentType.Alias; if (mediaItem == null) { return(BadRequest(string.Format("Couldn't find the media item to rotate"))); } var umbracoFile = mediaItem.GetValue <string>("umbracoFile"); if (String.IsNullOrEmpty(umbracoFile)) { return(BadRequest(string.Format("Couldn't retrieve the umbraco file details of the item to rotate"))); } //read in the filepath from umbracoFile var filePath = String.Empty; if (umbracoFile.DetectIsJsonish()) { isCropper = true; try { imageCrops = JsonConvert.DeserializeObject <ImageCropDataSet>(umbracoFile, new JsonSerializerSettings { Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal }); } catch (Exception ex) { LogHelper.Error(typeof(PirouetteController), "Could not parse the json string: " + umbracoFile, ex); } filePath = imageCrops.Src; } else // not cropper { filePath = umbracoFile; } if (String.IsNullOrEmpty(filePath)) { return(BadRequest("Path to media Item not found")); } // use mediaFileSystem to get path string fullPath = mediaFileSystem.GetFullPath(filePath); var fileName = mediaFileSystem.GetFileName(filePath); // get new filename based on complicated rules of how much it's been rotated :-) // creating a new filename for the rotation should avoid file locks when saving the image var newFileName = GetNewRotatedFileName(fileName, turns); // determine if a file already exists with our new rotated name in the same path we're going to save it in var rotatedFileExists = mediaFileSystem.FileExists(fullPath.Replace(fileName, newFileName)); using (ImageFactory imageFactory = new ImageFactory(false)) { try { if (rotateInstruction.CreateNewMediaItem) { // checkbox to create a new media item for the rotation was checked // so lets rotate the file, converted to a 'PostedFile' // and save to a new Umbraco Media Item var imageToRotate = imageFactory.Load(fullPath); var ms = new MemoryStream(); imageToRotate.Rotate(turns * 90).Save(ms); ms.Position = 0; var memoryStreamPostedFile = new MemoryStreamPostedFile(ms, newFileName); var newMediaItem = mediaService.CreateMediaWithIdentity(mediaItem.Name + "_rotated" + (turns * 90).ToString(), mediaItem.ParentId, mediaItemAlias); newMediaItem.SetValue("umbracoFile", memoryStreamPostedFile); mediaService.Save(newMediaItem); ms.Dispose(); // return new media id return(Ok(newMediaItem.Id)); } else { // rotate the existing media item var newFilePath = fullPath.Replace(fileName, newFileName); //only need to rotate and save the file if it doesn't already exist if (!rotatedFileExists) { //lets rotate and save the file var imageToRotate = imageFactory.Load(fullPath); var ms = new MemoryStream(); imageToRotate.Rotate(turns * 90).Save(ms); ms.Position = 0; //overwrite the file if it already exists, though we checked this earlier // use mediaFileSystem Add File to do the saving mediaFileSystem.AddFile(newFilePath, ms, true); ms.Dispose(); // an odd number of turns requires us to switch width and height if (turns == 1 || turns == 3) { mediaItem.SetValue("umbracoWidth", imageToRotate.Image.Width); mediaItem.SetValue("umbracoHeight", imageToRotate.Image.Height); } } //we have a different url for our media - update underlying mediaitem to point to new file if (isCropper) { imageCrops.Src = imageCrops.Src.Replace(fileName, newFileName); mediaItem.SetValue("umbracoFile", JsonConvert.SerializeObject(imageCrops)); } else // not cropper { mediaItem.SetValue("umbracoFile", filePath.Replace(fileName, newFileName)); } //update the media item mediaService.Save(mediaItem); } } catch (Exception ex) { Logger.Error(typeof(PirouetteController), "Error rotating image", ex); return(BadRequest(ex.Message)); } } return(Ok(mediaItem.Id)); }