Exemple #1
0
        public IHttpActionResult CreateNewMedia(ImageFilterInstruction imageFilterInstruction)
        {
            var mediaId      = imageFilterInstruction.MediaId;
            var queryString  = imageFilterInstruction.QueryString;
            var mediaService = Services.MediaService;

            // 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 adjust")));
            }
            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 adjust")));
            }

            bool   isNew          = mediaItem.Id <= 0;
            string serverFilePath = GetServerFilePath(mediaItem, isNew);
            string newFileName    = Guid.NewGuid() + Path.GetExtension(serverFilePath);

            if (serverFilePath != null)
            {
                using (ImageFactory imageFactory = new ImageFactory(false))
                {
                    var imageToAdjust = imageFactory.Load(serverFilePath);
                    var ms            = new MemoryStream();

                    NameValueCollection settings = HttpUtility.ParseQueryString(imageFilterInstruction.QueryString);

                    string setting = settings.GetKey(0);
                    string value   = settings.Get(0);

                    switch (setting)
                    {
                    case "brightness":
                        imageToAdjust.Brightness(int.Parse(value)).Save(ms);
                        break;

                    case "contrast":
                        imageToAdjust.Contrast(int.Parse(value)).Save(ms);
                        break;

                    case "filter":
                        //TODO
                        imageToAdjust.Save(ms);
                        break;

                    case "flip":
                        imageToAdjust.Flip(flipVertically: value == "vertical", flipBoth: value == "both");
                        break;

                    case "rotate":
                        imageToAdjust.Rotate(int.Parse(value));
                        break;
                    }

                    ms.Position = 0;
                    var    memoryStreamPostedFile = new MemoryStreamPostedFile(ms, newFileName);
                    string newMediaName           = mediaItem.Name + queryString.Replace("?", " ").Replace("=", " ");
                    var    newMediaItem           = mediaService.CreateMedia(newMediaName, mediaItem.ParentId, mediaItemAlias);
                    newMediaItem.SetValue(Constants.Conventions.Media.File, memoryStreamPostedFile);
                    mediaService.Save(newMediaItem);
                    ms.Dispose();
                    return(Ok(newMediaItem.Id));
                }
            }
            return(BadRequest(string.Format("Couldn't find the media item to adjust")));
        }
        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));
        }