• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ResizeSettings类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ResizeSettings的典型用法代码示例。如果您正苦于以下问题:C# ResizeSettings类的具体用法?C# ResizeSettings怎么用?C# ResizeSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ResizeSettings类属于命名空间,在下文中一共展示了ResizeSettings类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SaveImage

        public Image SaveImage(HttpServerUtilityBase server, HttpPostedFileBase file)
        {
            string largeUploadFolder = server.MapPath("~/assets/images/large");
            string mediumUploadFolder = server.MapPath("~/assets/images/medium");
            string thumbUploadFolder = server.MapPath("~/assets/images/thumb");
            if (!Directory.Exists(largeUploadFolder)) Directory.CreateDirectory(largeUploadFolder);
            if (!Directory.Exists(mediumUploadFolder)) Directory.CreateDirectory(mediumUploadFolder);
            if (!Directory.Exists(thumbUploadFolder)) Directory.CreateDirectory(thumbUploadFolder);

            //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
            ResizeSettings largeSettings = new ResizeSettings("maxwidth=800&maxheight=800");
            ResizeSettings mediumSettings = new ResizeSettings("maxwidth=300&maxheight=300&scale=both");
            ResizeSettings thumbSettings = new ResizeSettings("width=100&height=100&crop=auto");

            //var uniqueName = System.Guid.NewGuid().ToString();
            string uniqueName = PathUtils.RemoveExtension(file.FileName) + "_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss");
            string largeFilePath = Path.Combine(largeUploadFolder, uniqueName);
            string mediumFilePath = Path.Combine(mediumUploadFolder, uniqueName);
            string thumbFilePath = Path.Combine(thumbUploadFolder, uniqueName);

            //Let the image builder add the correct extension based on the output file type (which may differ).
            var large = ImageBuilder.Current.Build(file, largeFilePath, largeSettings, false, true);
            var med = ImageBuilder.Current.Build(file, mediumFilePath, mediumSettings, false, true);
            var thumb = ImageBuilder.Current.Build(file, thumbFilePath, thumbSettings, false, true);

            Image img = new Image(PathUtils.RemoveExtension(file.FileName), ResolveRelativePath(server, large), ResolveRelativePath(server, med), ResolveRelativePath(server, thumb));
            Repo.Save(img);
            return img;
        }
开发者ID:s-leonard,项目名称:Tarts,代码行数:29,代码来源:ImageHelper.cs


示例2: CreateIfSuitable

 public IEncoder CreateIfSuitable(ResizeSettings settings, object original)
 {
     if ("webp".Equals(settings.Format, StringComparison.OrdinalIgnoreCase)) {
         return new WebPEncoderPlugin(settings);
     }
     return null;
 }
开发者ID:stukalin,项目名称:ImageResizer,代码行数:7,代码来源:WebPEncoder.cs


示例3: Index

        public FileContentResult Index(string filename, int w = 0, int h = 0)
        {
            try
            {
                string contentType = "";
                var filePath = new FileInfo(Server.MapPath("~/App_Data/") + filename);

                var index = filename.LastIndexOf(".") + 1;
                var extension = filename.Substring(index).ToUpperInvariant();

                // Fix for IE not handling jpg image types
                contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);

                Bitmap bmImage = null;
                if (w > 0 && h > 0)
                {
                    //&format={3}
                    string querySetting = String.Format("width={0};height={1};crop={2}", w, h, "auto");
                    var resizeSetting = new ResizeSettings(querySetting);
                    bmImage = ImageBuilder.Current.Build(filePath.FullName, resizeSetting);
                }
                else
                {
                    bmImage = ImageBuilder.Current.LoadImage(filePath.FullName, new ResizeSettings());
                }
                byte[] byteArray = ImageHelpers.BitmapToBytes(bmImage);
                return File(byteArray, contentType);
            }
            catch
            {
                throw new FileNotFoundException();

            }
        }
开发者ID:duyphuong13,项目名称:IB,代码行数:34,代码来源:ImageController.cs


示例4: UploadFiles

        public void UploadFiles(string settingsForImages)
        {
            if (!IsPostBack) return;

            Guid lastUpload = Guid.Empty;
            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                if (file.ContentLength <= 0) continue; //Yes, 0-length files happen.

                if (Config.Current.Pipeline.IsAcceptedImageType(file.FileName) && settingsForImages != null) {
                    //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
                    ResizeSettings resizeCropSettings = new ResizeSettings(settingsForImages);

                    using (MemoryStream ms = new MemoryStream()) {
                        //Resize the image
                        ImageBuilder.Current.Build(file, ms, resizeCropSettings);
                        //Upload the byte array to SQL
                        lastUpload = StoreFile(ms.ToArray(), ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, file.FileName).Extension, file.FileName);
                    }
                } else {
                    //It's not an image - upload as-is.
                    lastUpload = StoreFile(StreamExtensions.CopyToBytes(file.InputStream), PathUtils.GetExtension(file.FileName).TrimStart('.'), file.FileName);

                }
            }

            if (lastUpload != Guid.Empty) Response.Redirect(ResolveUrl("~/"));
        }
开发者ID:stukalin,项目名称:ImageResizer,代码行数:29,代码来源:Upload.aspx.cs


示例5: ResizeImage

        public static Bitmap ResizeImage(Stream imageStream, PhotoSize size)
        {
            var maxHeight = 0;
            var maxWidth = 0;

            switch (size)
            {
                case PhotoSize.Medium:
                    maxHeight = 225;
                    maxWidth = 225;
                    break;

                case PhotoSize.Fullsize:
                    break;

                default:
                    maxHeight = 125;
                    maxWidth = 125;
                    break;
            }
            var rs = new ResizeSettings();
            if (maxHeight > 0)
            {
                rs.MaxHeight = maxHeight;
                rs.MaxWidth = maxWidth;
            }            
            return ImageBuilder.Current.Build(imageStream, rs);
        }
开发者ID:August2008,项目名称:August2008.org,代码行数:28,代码来源:SiteHelper.cs


示例6: Generate

        //
        // GET: /Image/

        public FileResult Generate(string source, int width, int height)
        {
            string url = Uri.UnescapeDataString(source);
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream stream = httpWebReponse.GetResponseStream();

            var quality = 80;
            byte[] resized;
            using (var outStream = new MemoryStream())
            {
                var settings = new ResizeSettings
                {
                    Mode = FitMode.Crop,
                    Width = width,
                    Height = height,
                    Format = "jpg"
                };
                settings.Add("quality", quality.ToString());
                ImageBuilder.Current.Build(stream, outStream, settings);
                resized = outStream.ToArray();
            }

            stream.Dispose();

            return new FileStreamResult(new MemoryStream(resized, 0, resized.Length), "image/jpeg");
        }
开发者ID:agentvnod,项目名称:tfctvoldcode,代码行数:30,代码来源:ImageController.cs


示例7: GetImage

        public Task<HttpResponseMessage> GetImage(string artistName, CancellationToken token)
        {
            return GetImageList(artistName, token).ContinueWith(imageTask =>
            {
                var response = new HttpResponseMessage();
                var client = new WebClient();
                var firstImage = imageTask.Result.FirstOrDefault();

                if (!string.IsNullOrEmpty(firstImage))
                {
                    var uri = new Uri(firstImage, UriKind.RelativeOrAbsolute);

                    if (!uri.IsAbsoluteUri)
                    {
                        uri = new Uri("http://2fm.rte.ie/images/default-album-art.jpg");
                    }

                    var query = Request.RequestUri.ParseQueryString();
                    var settings = new ResizeSettings(query);
                    var remote = RemoteReaderPlugin.Current.CreateSignedUrl(uri.ToString().Replace(" ", "%20"), settings);
                    var r = Request.CreateResponse(HttpStatusCode.Moved);
                    r.Headers.Location = new Uri(remote, UriKind.RelativeOrAbsolute);

                    return r;
                    //var imageStream = client.OpenRead(firstImage);
                    //response.Content = new StreamContent(imageStream);
                    //response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    //return response;
                }

                response.Content = new StreamContent(new MemoryStream());
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                return response;
            });
        }
开发者ID:torshy,项目名称:TRock.Party,代码行数:35,代码来源:BackdropController.cs


示例8: FreeImageEncoderPlugin

        public FreeImageEncoderPlugin(ResizeSettings settings, object original)
        {
            ImageFormat originalFormat = DefaultEncoder.GetOriginalFormat(original);
            if (!IsValidOutputFormat(originalFormat)) originalFormat = ImageFormat.Jpeg;//No valid info available about the original format. Use Jpeg.

            //What format was specified?
            ImageFormat requestedFormat = DefaultEncoder.GetRequestedFormat(settings.Format, originalFormat); //fallback to originalFormat if not specified.
            if (!IsValidOutputFormat(requestedFormat))
                throw new ArgumentException("An unrecognized or unsupported output format (" + (settings.Format != null ? settings.Format : "(null)") + ") was specified in 'settings'.");
            this.format =  FreeImage.GetFormat(requestedFormat);

            //Parse JPEG settings.
            int quality = 90;
            if (string.IsNullOrEmpty(settings["quality"]) || !int.TryParse(settings["quality"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out quality)) quality = 90;
            if (format == FREE_IMAGE_FORMAT.FIF_JPEG) {
                if (quality >= 100) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                else if (quality >= 75)
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                else if (quality >= 50) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                else if (quality >= 25) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                else encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;

                if ("true".Equals(settings["progressive"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE;

                if ("411".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_411;
                if ("420".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420;
                if ("422".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_422;
                if ("444".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;
            }
            if (string.IsNullOrEmpty(settings["colors"]) || !int.TryParse(settings["colors"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out colors)) colors = -1;

            if (format == FREE_IMAGE_FORMAT.FIF_GIF) {
                //encodingOptions = FREE_IMAGE_SAVE_FLAGS.
            }
        }
开发者ID:eakova,项目名称:resizer,代码行数:35,代码来源:FreeImageEncoder.cs


示例9: PrettyGifs

        public PrettyGifs(ResizeSettings settings, object original)
        {
            this.query = new ResizeSettings(settings);
            ResizeSettings q = settings;
            //Parse output format
            OutputFormat = GetFormatIfSuitable(settings, original);
            //Parse colors
            int colors = -1;
            if (!string.IsNullOrEmpty(q["colors"]))
                if (int.TryParse(q["colors"], NumberStyles.Integer,NumberFormatInfo.InvariantInfo, out colors))
                    this.Colors = colors;
            //Parse dither settings
            if (!string.IsNullOrEmpty(q["dither"])) {
                if ("true".Equals(q["dither"], StringComparison.OrdinalIgnoreCase))
                    this.Dither = true;
                else if ("4pass".Equals(q["dither"], StringComparison.OrdinalIgnoreCase))
                    this.FourPassDither = true;
                else {
                    int dither;
                    if (int.TryParse(q["dither"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out dither)) {
                        DitherPercent = dither;
                        Dither = true;
                    }
                }

            }

            PreservePalette = q.Get<bool>("preservePalette", PreservePalette);
            if (PreservePalette && original is Image && ((Image)original).Palette.Entries.Length > 0) {
                originalPalette = ((Image)original).Palette;
            }
        }
开发者ID:stukalin,项目名称:ImageResizer,代码行数:32,代码来源:PrettyGifs.cs


示例10: SaveFile

        public static string SaveFile(HttpPostedFileBase hpf, Photo_types type)
        {
            string filename = "",
                   ext = "",
                   savedFileName = "";

            if (hpf.ContentLength == 0)
                return "";

            var settings = new ResizeSettings
            {
                MaxWidth = 450,
                MaxHeight = 350,
                Format = "jpg"
            };

            DateTime now = DateTime.Now;
            ext = Path.GetExtension(hpf.FileName);
            filename = type.ToString() + "-" + now.Millisecond + now.Second + now.Hour + now.Minute + now.Day + now.Year + ext;

            savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + CMS_TEMP_PATH, filename);

            ImageBuilder.Current.Build(hpf.InputStream, savedFileName, settings);
            //hpf.SaveAs(savedFileName);

            return filename;
        }
开发者ID:DCruz22,项目名称:MusicHub,代码行数:27,代码来源:FilesHelper.cs


示例11: ImageLayer

 public ImageLayer(NameValueCollection attrs, Config c)
     : base(attrs)
 {
     Path = attrs["path"];
         this.c = c;
         if (!string.IsNullOrEmpty(attrs["imageQuery"])) ImageQuery = new ResizeSettings(attrs["imageQuery"]);
 }
开发者ID:kevjett,项目名称:Resizer,代码行数:7,代码来源:ImageLayer.cs


示例12: Edit

		public ActionResult Edit(EditModel model)
		{
			if (!ModelState.IsValid)
			{
				return View(model);
			}

			// Get the About entity if it exists, so ImageUrl doesn't get overriden to null if no image is selected and user is saving in json instead of sql.
			var about = Services.About.Exists(model.Title) ? Services.About.GetByTitle(model.Title) : new About();
			about.Name = model.Name;
			about.Title = model.Title;
			about.Content = model.Content;
			// Save the image in blob storage
			if (model.Image != null)
			{
				var image = new NBlog.Web.Application.Service.Entity.Image();
				var fileName = Path.GetFileName(model.Image.FileName);
				// Scale the image before saving
				using (var scaledImageStream = new MemoryStream())
				{
					var settings = new ResizeSettings(200, 150, FitMode.None, "jpg");
					ImageBuilder.Current.Build(model.Image.InputStream, scaledImageStream, settings);
					image.StreamToUpload = scaledImageStream;
					// Set FileName to save as, gets read as a repository key
					image.FileName = fileName;
					Services.Image.Save(image);
				}
				// Get the url to link to the About Entity
				about.ImageUrl = Services.Image.GetByFileName(fileName).Uri;
			}
			Services.About.Save(about);

			return RedirectToAction("Index", "About");
		}
开发者ID:skyline9002,项目名称:NBlog,代码行数:34,代码来源:AboutController.cs


示例13: PostDecodeStream

        protected override RequestedAction PostDecodeStream(ref Bitmap b, ResizeSettings settings)
        {
            if (!"true".Equals(settings["autorotate"], StringComparison.OrdinalIgnoreCase)) return RequestedAction.None;

            int propertyId = 0x0112;
            PropertyItem pi;
            try {
                pi = b.GetPropertyItem(propertyId);
            } catch (ArgumentException) {
                return RequestedAction.None;
            }
            if (pi == null) return RequestedAction.None;

            int total = 0;

            foreach (byte by in pi.Value) total += by; //Does not handle values larger than 255, but it doesn't need to, and is endian-agnostic.

            if (total == 8) b.RotateFlip(RotateFlipType.Rotate270FlipNone);
            if (total == 3) b.RotateFlip(RotateFlipType.Rotate180FlipNone);
            if (total == 6) b.RotateFlip(RotateFlipType.Rotate90FlipNone);

            if (total == 2) b.RotateFlip(RotateFlipType.RotateNoneFlipX);
            if (total == 4) b.RotateFlip(RotateFlipType.Rotate180FlipX);
            if (total == 5) b.RotateFlip(RotateFlipType.Rotate270FlipY);
            if (total == 7) b.RotateFlip(RotateFlipType.Rotate90FlipY);

            b.RemovePropertyItem(propertyId);

            return RequestedAction.None;
        }
开发者ID:stukalin,项目名称:ImageResizer,代码行数:30,代码来源:AutoRotate.cs


示例14: ImageRequestAction

 public ImageRequestAction(string virtualPath, NameValueCollection query, IPipelineConfig conf = null)
 {
     this.conf = (conf == null) ? Config.Current.Pipeline : conf;
     ReauthorizeFinalPath = true;
     Source = virtualPath;
     Settings = new ResizeSettings(query);
 }
开发者ID:kevjett,项目名称:Resizer,代码行数:7,代码来源:ImageRequestAction.cs


示例15: FileStorage

        public FileStorage(ISettings settings)
        {
            _settings = settings;
            
            _resizeSettings = new ResizeSettings {
                    MaxWidth = settings.ThumbnailSize,
                    MaxHeight = settings.ThumbnailSize, 
                    Format = "jpg"
                };
            _resizeSettings.Add("quality", ImageQuality);

            //create FullsizedImagesFolder & SmallImagesFolder subfolders
            string largeFilesFolder = Path.Combine(settings.ImagesLocalFolder, FullsizedImagesFolder);
            string smallFilesFolder = Path.Combine(settings.ImagesLocalFolder, SmallImagesFolder);

            if (!Directory.Exists(largeFilesFolder))
                Directory.CreateDirectory(largeFilesFolder);
            if (!Directory.Exists(smallFilesFolder))
                Directory.CreateDirectory(smallFilesFolder);
            
            _lastPhoto = Directory
                .GetFiles(largeFilesFolder, "*.jpg")
                .Select(i => int.Parse(Path.GetFileNameWithoutExtension(i).ToLower().Replace(".jpg", "")))
                .OrderByDescending(i => i)
                .FirstOrDefault();

            if (_lastPhoto < 1)
                _lastPhoto = 1;
        }
开发者ID:EgorBo,项目名称:CrossChat-Xamarin.Forms,代码行数:29,代码来源:FileStorage.cs


示例16: Get

        public HttpResponseMessage Get(Guid imageId, int width, int height)
        {
            using (var context = new ApplicationDbContext())
            {
                var image = context.Images
                    .Single(i => i.Id == imageId);

                var settings = new ResizeSettings
                {
                    Format = "jpg",
                    Mode = FitMode.Stretch,
                    Width = width,
                    Height = height,
                    Scale = ScaleMode.Both
                };

                var stream = new MemoryStream();
                ImageBuilder.Current.Build(image.Data, stream, settings);
                stream.Position = 0;

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                return result;
            }

        }
开发者ID:envman,项目名称:Eventy.Server,代码行数:29,代码来源:ImageController.cs


示例17: ResizeImage

        /// <summary>
        /// The resize image.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="width">
        /// The width.
        /// </param>
        /// <param name="height">
        /// The height.
        /// </param>
        /// <returns>
        /// The <see cref="byte[]"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public byte[] ResizeImage(byte[] source, int width, int height)
        {
            byte[] result = null;
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            using (var sourceStream = new MemoryStream(source.Length))
            {
                sourceStream.Write(source, 0, source.Length);
                sourceStream.Seek(0, SeekOrigin.Begin);
                var settings = new ResizeSettings();
                settings.Width = width;
                settings.Height = height;
                settings.Mode = FitMode.Crop;
                using (var destinationStream = new MemoryStream())
                {
                    ImageBuilder.Current.Build(sourceStream, destinationStream, settings);
                    result = destinationStream.ToArray();
                }

                return result;
            }
        }
开发者ID:RamanBut-Husaim,项目名称:TermWork-SignalRChat,代码行数:42,代码来源:ImageResizingService.cs


示例18: ImageBuilder

        public static void ImageBuilder(string imageFile, ImageType type, bool IsInTempFolder,AspxCommonInfo aspxCommonObj)
        {

            try
            {
                bool disposeSource = true;
                bool addFileExtensions = true;
                string tempFolder = string.Empty;
                string filename = imageFile;
                bool isExistImage = false;
                var resizeSetings = new ResizeSettings();
                resizeSetings.Format = "jpg";
                resizeSetings.Mode = FitMode.Max;
                switch (type)
                {
                    case ImageType.Large:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Large, filename);
                            if (!(isExistImage))
                            {
                               ImageSettings imgStng=new ImageSettings(aspxCommonObj);
                               resizeSetings.MaxWidth = imgStng.itemLargeThumbNailWidth;
                               resizeSetings.MaxHeight = imgStng.itemLargeThumbNailHeight;
                               copyOriginalImageToRespectives(ImageType.Large, filename, resizeSetings,disposeSource, addFileExtensions);
                            }
                            break;
                        }
                    case ImageType.Medium:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Medium, filename);
                            if (!(isExistImage))
                            {
                                ImageSettings imgStng = new ImageSettings(aspxCommonObj);
                                resizeSetings.MaxWidth = imgStng.itemMediumThumbNailWidth;
                                resizeSetings.MaxHeight = imgStng.itemMediumThumbNailHeight;
                                copyOriginalImageToRespectives(ImageType.Medium, filename, resizeSetings, disposeSource, addFileExtensions);
                            }
                            break;
                        }
                    case ImageType.Small:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Medium, filename);
                            if (!(isExistImage))
                            {
                                ImageSettings imgStng = new ImageSettings(aspxCommonObj);
                                resizeSetings.MaxWidth = imgStng.itemSmallThumbNailWidth;
                                resizeSetings.MaxHeight = imgStng.itemSmallThumbNailHeight;
                                copyOriginalImageToRespectives(ImageType.Medium, filename, resizeSetings, disposeSource, addFileExtensions);
                            }
                            break;
                        }

                }

            }
            catch
            {
            }
        }
开发者ID:xiaoxiaocoder,项目名称:AspxCommerce2.7,代码行数:59,代码来源:InterceptImage.cs


示例19: PostSalonImage

        // POST: api/SaveImages + ?id!
        //[Route("api/SaveImages/{id:int}")]
        public async Task<IHttpActionResult> PostSalonImage(int id, Boolean main, [FromUri]string username)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Check if the request contains multipart/form-data.
            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

                foreach (var item in streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)))
                {
                    Stream stPictureSource = new MemoryStream(await item.ReadAsByteArrayAsync());

                    // Resize for Picture
                    MemoryStream stPictureDest = new MemoryStream();
                    var pictureSettings = new ResizeSettings
                    {
                        MaxWidth = 1000,
                        MaxHeight = 1000,
                        Mode = FitMode.Max
                    };
                    ImageBuilder.Current.Build(stPictureSource, stPictureDest, pictureSettings);

                    string fileName = item.Headers.ContentDisposition.FileName;

                    fileName = fileName.Replace("\"", string.Empty);

                    string ext = Path.GetExtension(fileName);

                    string newFileName = Guid.NewGuid().ToString() + ext;

                    File.WriteAllBytes(HostingEnvironment.MapPath("~/Images/SalonImages/" + newFileName), stPictureDest.ToArray());

                    db.SalonImages.Add(new SalonImage
                    {
                        AddedOn = DateTime.Now,
                        CreateBy = username,
                        ImageName = fileName,
                        ImagePath = newFileName,
                        IsDeleted = false,
                        IsMain = main,
                        SalonID = id,

                    });
                }

                await db.SaveChangesAsync();
                return Ok();
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

        }
开发者ID:lachezar1990,项目名称:test8,代码行数:61,代码来源:SaveImagesController.cs


示例20: ResizeToStream

 public Stream ResizeToStream(string instructions)
 {
     var settings = new ResizeSettings(instructions);
     var ostream = new MemoryStream();
     ImageBuilder.Current.Build(Bits, ostream, settings);
     ostream.Position = 0;
     return ostream;
 }
开发者ID:stevesloka,项目名称:bvcms,代码行数:8,代码来源:Image.cs



注:本文中的ResizeSettings类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Resolution类代码示例发布时间:2022-05-24
下一篇:
C# ResizeDirection类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap