private string ProcessFile(ContentPropertyData editorValue, ContentItemFile file, string currentPath, Guid cuid, Guid puid) { // process the file // no file, invalid file, reject change if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false) { return(null); } // get the filepath // in case we are using the old path scheme, try to re-use numbers (bah...) var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path using (var filestream = File.OpenRead(file.TempFilePath)) { _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite! var ext = _mediaFileSystem.GetExtension(filepath); if (_mediaFileSystem.IsImageFile(ext)) { var preValues = editorValue.PreValues.FormatAsDictionary(); var sizes = preValues.Any() ? preValues.First().Value.Value : string.Empty; using (var image = Image.FromStream(filestream)) _mediaFileSystem.GenerateThumbnails(image, filepath, sizes); } // all related properties (auto-fill) are managed by ImageCropperPropertyEditor // when the content is saved (through event handlers) } return(filepath); }
public void writeContents(int id, string filename, Byte[] contents, string username, string password) { Authenticate(username, password); filename = filename.Replace("/", global::Umbraco.Core.IO.IOHelper.DirSepChar.ToString()); filename = filename.Replace(@"\", global::Umbraco.Core.IO.IOHelper.DirSepChar.ToString()); filename = filename.Substring(filename.LastIndexOf(global::Umbraco.Core.IO.IOHelper.DirSepChar) + 1, filename.Length - filename.LastIndexOf(global::Umbraco.Core.IO.IOHelper.DirSepChar) - 1).ToLower(); var m = new Media(id); var numberedFolder = MediaSubfolderCounter.Current.Increment(); var path = _fs.GetRelativePath(numberedFolder.ToString(CultureInfo.InvariantCulture), filename); var stream = new MemoryStream(); stream.Write(contents, 0, contents.Length); stream.Seek(0, 0); _fs.AddFile(path, stream); m.getProperty("umbracoFile").Value = _fs.GetUrl(path); m.getProperty("umbracoExtension").Value = Path.GetExtension(filename).Substring(1); m.getProperty("umbracoBytes").Value = _fs.GetSize(path); m.Save(); }
private string ProcessFile(ContentPropertyData editorValue, ContentItemFile file, string currentPath, Guid cuid, Guid puid) { // process the file // no file, invalid file, reject change if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false) { return(null); } // get the filepath // in case we are using the old path scheme, try to re-use numbers (bah...) var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path using (var filestream = File.OpenRead(file.TempFilePath)) { _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite! var ext = _mediaFileSystem.GetExtension(filepath); if (_mediaFileSystem.IsImageFile(ext) && ext != ".svg") { var preValues = editorValue.PreValues.FormatAsDictionary(); var sizes = preValues.Any() ? preValues.First().Value.Value : string.Empty; try { using (var image = Image.FromStream(filestream)) _mediaFileSystem.GenerateThumbnails(image, filepath, sizes); } catch (ArgumentException ex) { // send any argument errors caused by the thumbnail generation to the log instead of failing miserably LogHelper.WarnWithException <ImageCropperPropertyValueEditor>("Could not extract image thumbnails.", ex); } } // all related properties (auto-fill) are managed by ImageCropperPropertyEditor // when the content is saved (through event handlers) } return(filepath); }
private static void SaveJpeg(string path, Bitmap img, long quality) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality); // Jpeg image codec ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); if (jpegCodec == null) return; EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; using (var fileStream = new MemoryStream()) { img.Save(fileStream, jpegCodec, encoderParams); fileStream.Position = 0; _fs.AddFile(path, fileStream, true); } }
private static Tuple <int, int, string> GenerateThumbnail(MediaFileSystem fileSystem, Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string extension, string thumbnailFileName, bool useFixedDimensions) { // Generate thumbnail float f = 1; if (!useFixedDimensions) { var fx = (float)image.Size.Width / (float)maxWidthHeight; var fy = (float)image.Size.Height / (float)maxWidthHeight; // must fit in thumbnail size f = Math.Max(fx, fy); //if (f < 1) f = 1; } var widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f); // fixes for empty width or height if (widthTh == 0) { widthTh = 1; } if (heightTh == 0) { heightTh = 1; } // Create new image with best quality settings var bp = new Bitmap(widthTh, heightTh); var g = Graphics.FromImage(bp); g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; // Copy the old image to the new and resized var rect = new Rectangle(0, 0, widthTh, heightTh); g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); // Copy metadata var imageEncoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo codec = null; if (extension.ToLower() == "png" || extension.ToLower() == "gif") { codec = imageEncoders.Single(t => t.MimeType.Equals("image/png")); } else { codec = imageEncoders.Single(t => t.MimeType.Equals("image/jpeg")); } // Set compresion ratio to 90% var ep = new EncoderParameters(); ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L); // Save the new image using the dimensions of the image string newFileName = thumbnailFileName.Replace("UMBRACOSYSTHUMBNAIL", string.Format("{0}x{1}", widthTh, heightTh)); var ms = new MemoryStream(); bp.Save(ms, codec, ep); ms.Seek(0, 0); fileSystem.AddFile(newFileName, ms); ms.Close(); bp.Dispose(); g.Dispose(); return(new Tuple <int, int, string>(widthTh, heightTh, newFileName)); }
/// <summary> /// Converts the value received from the editor into the value can be stored in the database. /// </summary> /// <param name="editorValue">The value received from the editor.</param> /// <param name="currentValue">The current value of the property</param> /// <returns>The converted value.</returns> /// <remarks> /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para> /// <para>The <paramref name="editorValue"/> is value passed in from the editor. We normally don't care what /// the editorValue.Value is set to because we are more interested in the files collection associated with it, /// however we do care about the value if we are clearing files. By default the editorValue.Value will just /// be set to the name of the file - but again, we just ignore this and deal with the file collection in /// editorValue.AdditionalData.ContainsKey("files")</para> /// <para>We only process ONE file. We understand that the current value may contain more than one file, /// and that more than one file may be uploaded, so we take care of them all, but we only store ONE file. /// Other places (FileUploadPropertyEditor...) do NOT deal with multiple files, and our logic for reusing /// folders would NOT work, etc.</para> /// </remarks> public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { currentValue = currentValue ?? string.Empty; // at that point, // currentValue is either empty or "/media/path/to/img.jpg" // editorValue.Value is { "clearFiles": true } or { "selectedFiles": "img1.jpg,img2.jpg" } // comparing them makes little sense // check the editorValue value to see whether we need to clear files var editorJsonValue = editorValue.Value as JObject; var clears = editorJsonValue != null && editorJsonValue["clearFiles"] != null && editorJsonValue["clearFiles"].Value <bool>(); var uploads = editorValue.AdditionalData.ContainsKey("files") && editorValue.AdditionalData["files"] is IEnumerable <ContentItemFile>; // nothing = no changes, return what we have already (leave existing files intact) if (clears == false && uploads == false) { return(currentValue); } // get the current file paths var currentPaths = currentValue.ToString() .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => _mediaFileSystem.GetRelativePath(x)) // get the fs-relative path .ToArray(); // if clearing, remove these files and return if (clears) { foreach (var pathToRemove in currentPaths) { _mediaFileSystem.DeleteFile(pathToRemove, true); } return(string.Empty); // no more files } // ensure we have the required guids if (editorValue.AdditionalData.ContainsKey("cuid") == false || // for the content item editorValue.AdditionalData.ContainsKey("puid") == false) // and the property type { throw new Exception("Missing cuid/puid additional data."); } var cuido = editorValue.AdditionalData["cuid"]; var puido = editorValue.AdditionalData["puid"]; if ((cuido is Guid) == false || (puido is Guid) == false) { throw new Exception("Invalid cuid/puid additional data."); } var cuid = (Guid)cuido; var puid = (Guid)puido; if (cuid == Guid.Empty || puid == Guid.Empty) { throw new Exception("Invalid cuid/puid additional data."); } // process the files var files = ((IEnumerable <ContentItemFile>)editorValue.AdditionalData["files"]).ToArray(); var newPaths = new List <string>(); const int maxLength = 1; // we only process ONE file for (var i = 0; i < maxLength /*files.Length*/; i++) { var file = files[i]; // skip invalid files if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false) { continue; } // get the filepath // in case we are using the old path scheme, try to re-use numbers (bah...) var reuse = i < currentPaths.Length ? currentPaths[i] : null; // this would be WRONG with many files var filepath = _mediaFileSystem.GetMediaPath(file.FileName, reuse, cuid, puid); // fs-relative path using (var filestream = File.OpenRead(file.TempFilePath)) { _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite! var ext = _mediaFileSystem.GetExtension(filepath); if (_mediaFileSystem.IsImageFile(ext) && ext != ".svg") { var preValues = editorValue.PreValues.FormatAsDictionary(); var sizes = preValues.Any() ? preValues.First().Value.Value : string.Empty; using (var image = Image.FromStream(filestream)) _mediaFileSystem.GenerateThumbnails(image, filepath, sizes); } // all related properties (auto-fill) are managed by FileUploadPropertyEditor // when the content is saved (through event handlers) newPaths.Add(filepath); } } // remove all temp files foreach (var file in files) { File.Delete(file.TempFilePath); } // remove files that are not there anymore foreach (var pathToRemove in currentPaths.Except(newPaths)) { _mediaFileSystem.DeleteFile(pathToRemove, true); } return(string.Join(",", newPaths.Select(x => _mediaFileSystem.GetUrl(x)))); }
protected UrlData newMediaObjectLogic( string blogid, string username, string password, FileData file) { if (ValidateUser(username, password)) { User u = new User(username); Channel userChannel = new Channel(username); UrlData fileUrl = new UrlData(); if (userChannel.ImageSupport) { Media rootNode; if (userChannel.MediaFolder > 0) { rootNode = new Media(userChannel.MediaFolder); } else { rootNode = new Media(u.StartMediaId); } // Create new media Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id); Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty); var filename = file.name.Replace("/", "_"); var relativeFilePath = UmbracoMediaFactory.GetRelativePath(fileObject.Id, filename); fileObject.Value = _fs.GetUrl(relativeFilePath); fileUrl.url = fileObject.Value.ToString(); if (!fileUrl.url.StartsWith("http")) { var protocol = GlobalSettings.UseSSL ? "https" : "http"; fileUrl.url = protocol + "://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + fileUrl.url; } _fs.AddFile(relativeFilePath, new MemoryStream(file.bits)); // Try updating standard file values try { string orgExt = ""; // Size if (m.getProperty(Constants.Conventions.Media.Bytes) != null) { m.getProperty(Constants.Conventions.Media.Bytes).Value = file.bits.Length; } // Extension if (m.getProperty(Constants.Conventions.Media.Extension) != null) { orgExt = ((string) file.name.Substring(file.name.LastIndexOf(".") + 1, file.name.Length - file.name.LastIndexOf(".") - 1)); m.getProperty(Constants.Conventions.Media.Extension).Value = orgExt.ToLower(); } // Width and Height // Check if image and then get sizes, make thumb and update database if (m.getProperty(Constants.Conventions.Media.Width) != null && m.getProperty(Constants.Conventions.Media.Height) != null && ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0) { int fileWidth; int fileHeight; using (var stream = _fs.OpenFile(relativeFilePath)) { Image image = Image.FromStream(stream); fileWidth = image.Width; fileHeight = image.Height; stream.Close(); try { m.getProperty(Constants.Conventions.Media.Width).Value = fileWidth.ToString(); m.getProperty(Constants.Conventions.Media.Height).Value = fileHeight.ToString(); } catch (Exception ex) { LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred reading the media stream", ex); } } } } catch (Exception ex) { LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred in newMediaObjectLogic", ex); } return(fileUrl); } else { throw new ArgumentException( "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support."); } } return(new UrlData()); }