/// <summary> /// 保存媒体文件 /// </summary> /// <param name="blogid"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="file"></param> /// <returns></returns> public UrlData newMediaObject(string blogid, string username, string password, FileData file) { //try //{ User user; if ((user = ValidUser(username, password)) != null) { const string imgExtPattern = "^gif|jpg|jpeg|png|bmp$"; //图片扩展名正则 const int maxImageFileSize = 48882; //最大47KB,超过47KB则保存为文件 UrlData uri; //获取扩展名 string ext = file.name.Substring(file.name.LastIndexOf(".") + 1); //返回图片格式的媒体文件 if (Regex.IsMatch(file.name, imgExtPattern)) { //将图片转为JPG格式并保存到内存流中 MemoryStream stream = new MemoryStream(file.bits); Bitmap originalImg, newImg; //创建原始图片 originalImg = new Bitmap(stream); //绘制新的图片 newImg = new Bitmap(originalImg.Width, originalImg.Height); Graphics g = Graphics.FromImage(newImg); g.Clear(Color.White); g.DrawImage(originalImg, new Point(0, 0)); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; //释放原图及内存流资源 originalImg.Dispose(); stream.Dispose(); //创建新的内存流,并将图片存到内存中 stream = new MemoryStream(); newImg.Save(stream, ImageFormat.Jpeg); //如果使用Base64存取数据且大小小于指定则存为Base64 if (EnableBase64Images && stream.Length < maxImageFileSize) { //将内存流转为Base64格式字符 string base64Str = Convert.ToBase64String(stream.ToArray()); uri = new UrlData { url = String.Format("data:image/jpeg;base64,{0}", base64Str) }; } else { //以文件方式存储图片 string dateStr; string dirPath = GetMediaObjectSavePath(this.siteId, out dateStr); //文件名称 string filePath = String.Format("{0}.{1}", String.Format("{0:hhmmfff}", DateTime.Now), "jpg"); //保存图片到文件 //EncoderParameters encodeParams = new EncoderParameters(1); //encodeParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); ////获取JPEG编码器 //ImageCodecInfo[] codes = ImageCodecInfo.GetImageDecoders(); //ImageCodecInfo _code = null; //foreach (ImageCodecInfo code in codes) //{ // if (String.Compare(code.MimeType, "image/jpeg", true) == 0) // _code = code; //} //newImg.Save(dirPath + filePath,_code,encodeParams); newImg.Save(dirPath + filePath, ImageFormat.Jpeg); uri = new UrlData { url = String.Format("/{0}s{1}/lw/{2}/{2}", CmsVariables.RESOURCE_PATH, this.siteId.ToString(), dateStr, filePath) }; } //释放资源 newImg.Dispose(); stream.Dispose(); //返回地址 return uri; } else { //检测或创建以日期为命名的目录 string dateStr; string dirPath = GetMediaObjectSavePath(this.siteId, out dateStr); string filePath = String.Format("{0}.{1}", String.Format("{0:hhmmfff}", DateTime.Now), ext); //保存文件 using (FileStream fs = new FileStream(dirPath + filePath, FileMode.OpenOrCreate, FileAccess.Write)) { fs.Write(file.bits, 0, file.bits.Length); fs.Flush(); fs.Dispose(); } return new UrlData { url = String.Format("/{0}s{1}/lw/{2}/{3}", CmsVariables.RESOURCE_PATH, this.siteId.ToString(), dateStr, filePath) }; } } //} //catch (Exception ex) //{ // new OPS.Log.LogFile(AppDomain.CurrentDomain.BaseDirectory + "log.txt").Append(ex.Message + "\r\n"); //} return default(UrlData); }
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 = _fs.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; 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 { } } } catch { } 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(); }
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); string _fullFilePath; string filename = file.name.Replace("/", "_"); // Generate file if (UmbracoSettings.UploadAllowDirectories) { // Create a new folder in the /media folder with the name /media/propertyid Directory.CreateDirectory( IOHelper.MapPath( SystemDirectories.Media + "/" + fileObject.Id)); _fullFilePath = IOHelper.MapPath( SystemDirectories.Media + "/" + fileObject.Id + "/" + filename); fileObject.Value = SystemDirectories.Media + "/" + fileObject.Id + "/" + filename; } else { filename = fileObject.Id + "-" + filename; _fullFilePath = IOHelper.MapPath(SystemDirectories.Media + "/" + filename); fileObject.Value = SystemDirectories.Media + "/" + filename; } fileUrl.url = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + IOHelper.ResolveUrl(fileObject.Value.ToString()); File.WriteAllBytes(_fullFilePath, file.bits); // Try updating standard file values try { string orgExt = ""; // Size if (m.getProperty("umbracoBytes") != null) m.getProperty("umbracoBytes").Value = file.bits.Length; // Extension if (m.getProperty("umbracoExtension") != null) { orgExt = ((string) file.name.Substring(file.name.LastIndexOf(".") + 1, file.name.Length - file.name.LastIndexOf(".") - 1)); m.getProperty("umbracoExtension").Value = orgExt.ToLower(); } // Width and Height // Check if image and then get sizes, make thumb and update database if (m.getProperty("umbracoWidth") != null && m.getProperty("umbracoHeight") != null && ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0) { int fileWidth; int fileHeight; FileStream fs = new FileStream(_fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); Image image = Image.FromStream(fs); fileWidth = image.Width; fileHeight = image.Height; fs.Close(); try { m.getProperty("umbracoWidth").Value = fileWidth.ToString(); m.getProperty("umbracoHeight").Value = fileHeight.ToString(); } catch { } } } catch { } 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(); }