public HttpResponseMessage GetThumbnail(string imagePath, int width) { if (false == string.IsNullOrWhiteSpace(imagePath) && imagePath.IndexOf("{{") < 0) { var image = Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); MemoryStream outStream = new MemoryStream(); byte[] photoBytes = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); // change imagePath with a valid image path ISupportedImageFormat format = new JpegFormat { Quality = 70 }; // convert to jpg var inStream = new MemoryStream(photoBytes); var imageFactory = new ImageFactory(preserveExifData: true); Size size = ResizeKeepAspect(image.Size, width, width); ResizeLayer resizeLayer = new ResizeLayer(size, ResizeMode.Max); imageFactory.Load(inStream) .Resize(resizeLayer) .Format(format) .Save(outStream); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(outStream); response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); return response; } else { return null; } }
private static string SpecialEffectImage(IMatrixFilter effectFilter, string imageFilePath, bool isActualSize) { var specialEffectImageFile = Util.TempPath.GetPath("fullsize_specialeffect"); using (var imageFactory = new ImageFactory()) { var image = imageFactory .Load(imageFilePath) .Image; var ratio = (float)image.Width / image.Height; if (isActualSize) { image = imageFactory .Resize(new Size((int)(768 * ratio), 768)) .Filter(effectFilter) .Image; } else { image = imageFactory .Resize(new Size((int)(300 * ratio), 300)) .Filter(effectFilter) .Image; } image.Save(specialEffectImageFile); } return specialEffectImageFile; }
private void ObviouslyTurnUpOnAuth_Load(object sender, EventArgs e) { // For better graphical effects and less flickering, introduce double buffering and better background image usage this.BackgroundImageLayout = ImageLayout.None; DoubleBufferManipulation.SetDoubleBuffered(panel1); this.BackgroundImage = Image.FromFile(Properties.Settings.Default.lock_path[Properties.Settings.Default.whoIsThisCrazyDoge]); accountName.Text = Properties.Settings.Default.username[Properties.Settings.Default.whoIsThisCrazyDoge]; enterButton.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); accountImg.BackgroundImage = Image.FromFile(Properties.Settings.Default.userimgacc_path[Properties.Settings.Default.whoIsThisCrazyDoge]); // Huge shoutout to the makers of the ImageProcessor library for this one. ImageFactory imgf = new ImageFactory(); Properties.Resources._20pertrans_lighterGray.Save("C:\\ProjectSnowshoes\\loginbacktemp.png"); imgf.Load("C:\\ProjectSnowshoes\\loginbacktemp.png"); imgf.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); panel1.BackgroundImage = imgf.Image; }
public byte[] Resize(byte[] originalImage, int width) { using (var originalImageStream = new MemoryStream(originalImage)) { using (var resultImage = new MemoryStream()) { using (var imageFactory = new ImageFactory()) { var createdImage = imageFactory .Load(originalImageStream); if (createdImage.Image.Width > width) { createdImage = createdImage .Resize(new ResizeLayer(new Size(width, 0), ResizeMode.Max)); } createdImage .Format(new JpegFormat { Quality = WebApplicationConstants.ImageQuality }) .Save(resultImage); } return resultImage.GetBuffer(); } } }
// GET: Photos public ActionResult Index(int id, int? height, int? width) { int h = (height ?? 325); int w = (width ?? 325); Staff staff = db.StaffList.Find(id); if (staff == null) { return new HttpNotFoundResult(); } if (staff.Photo != null) { Size size = new Size(w, h); byte[] rawImg; using (MemoryStream inStream = new MemoryStream(staff.Photo)) { using (MemoryStream outStream = new MemoryStream()) { using (ImageFactory imageFactory = new ImageFactory()) { imageFactory.Load(inStream) .Constrain(size) .Format(format) .Save(outStream); } rawImg = outStream.ToArray(); } } return new FileContentResult(rawImg, "image/jpeg"); } else { return null; } }
public async Task<byte[]> Resize(byte[] originalImage, int width) { return await Task.Run(() => { using (var originalImageStream = new MemoryStream(originalImage)) { using (var resultImage = new MemoryStream()) { using (var imageFactory = new ImageFactory()) { var createdImage = imageFactory .Load(originalImageStream); createdImage = createdImage .Resize(new ResizeLayer(new Size(width, 0), ResizeMode.Max)); createdImage .Format(new JpegFormat { Quality = GlobalConstants.ImageQuality }) .Save(resultImage); } return resultImage.GetBuffer(); } } }); }
private static string BlurImage(string imageFilePath, int degree) { if (degree == 0) { return imageFilePath; } var resizeImageFile = Util.TempPath.GetPath("fullsize_resize"); using (var imageFactory = new ImageFactory()) { var image = imageFactory .Load(imageFilePath) .Image; var ratio = (float)image.Width / image.Height; var targetHeight = Math.Round(MaxThumbnailHeight - (MaxThumbnailHeight - MinThumbnailHeight) / 100f * degree); var targetWidth = Math.Round(targetHeight * ratio); image = imageFactory .Resize(new Size((int)targetWidth, (int)targetHeight)) .Image; image.Save(resizeImageFile); } var blurImageFile = Util.TempPath.GetPath("fullsize_blur"); using (var imageFactory = new ImageFactory()) { var image = imageFactory .Load(resizeImageFile) .GaussianBlur(5) .Image; image.Save(blurImageFile); } return blurImageFile; }
static void Main(string[] args) { string path = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath; // ReSharper disable once AssignNullToNotNullAttribute string resolvedPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\input")); DirectoryInfo di = new DirectoryInfo(resolvedPath); if (!di.Exists) { di.Create(); } FileInfo[] files = di.GetFiles("*.gif"); foreach (FileInfo fileInfo in files) { byte[] photoBytes = File.ReadAllBytes(fileInfo.FullName); // ImageProcessor using (MemoryStream inStream = new MemoryStream(photoBytes)) { using (ImageFactory imageFactory = new ImageFactory()) { Size size = new Size(200, 200); ImageFormat format = ImageFormat.Gif; // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .Constrain(size) .Tint(Color.FromArgb(255, 106, 166, 204)) .Format(format) .Save(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\output", fileInfo.Name))); } } } }
/// <summary> /// Method used to crop image. /// </summary> /// <param name="inputImagePathString">input image path</param> /// <param name="outputImagePathName">ouput image path</param> /// <param name="x1">x</param> /// <param name="y1">y</param> /// <param name="width">widht of cropped image</param> /// <param name="height">height of cropped image</param> public static void CropImage(string inputImagePathString, String outputImagePathName, int x1, int y1, int width, int height) { byte[] photoBytes = File.ReadAllBytes(inputImagePathString); // Format is automatically detected though can be changed. ISupportedImageFormat format = new JpegFormat { Quality = 70 }; Rectangle rectangle = new Rectangle(x1, y1, width, height); using (MemoryStream inStream = new MemoryStream(photoBytes)) { using (MemoryStream outStream = new MemoryStream()) { // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .Crop(rectangle) .Format(format) .Save(outStream); FileStream fileStream = new FileStream(outputImagePathName, FileMode.Create); outStream.WriteTo(fileStream); fileStream.Close(); } // Do something with the stream. outStream.Close(); } } }
private static async Task<Tuple<Stream, Image>> ImageResize(string imageString, int quality, Func<System.Drawing.Image, Size> sizeCalculation) { var photoBytes = Base64ImageDataToByteArray(imageString); var format = new JpegFormat(); using (MemoryStream inStream = new MemoryStream(photoBytes)) { MemoryStream outStream = new MemoryStream(); int width; int height; using (ImageFactory imageFactory = new ImageFactory()) { imageFactory.Load(inStream) .Resize(sizeCalculation(imageFactory.Image)) .Format(format) .Quality(quality); System.Drawing.Image image = imageFactory.Image; width = image.Width; height = image.Height; imageFactory.Save(outStream); } return new Tuple<Stream, Models.Image>(outStream, new Image("bloblstorage", width, height)); // Do something with the stream. } }
/// <summary> /// 上传图片 /// </summary> /// <returns></returns> public async Task<IHttpActionResult> Post() { try { string fileName = Guid.NewGuid().ToString(); string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg"); ; string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg"); System.Drawing.Bitmap image = new System.Drawing.Bitmap(HttpContext.Current.Request.InputStream); image.Save(fileOrginalFile); using (var imageFactory = new ImageFactory(preserveExifData: true)) { System.Drawing.Size size = new System.Drawing.Size(800, 1600); ResizeLayer resize = new ResizeLayer(size, ResizeMode.Max); imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized800Name); } BlobHelper blob = new BlobHelper(BlobString.Portrait); string contentType = "image/jpeg"; await blob.UploadFile(fileResized800Name, fileName , contentType); //删除文件 File.Delete(fileOrginalFile); File.Delete(fileResized800Name); return Json(new { Code = 10000, Detail = "http://hdy.awblob.com/portrait/" + fileName }); } catch (Exception ex) { return Json(new { Code = 10, Message = "上传失败" }); } }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { image = new ImageFactory(); image.Load(openFileDialog1.FileName); pictureBox1.Image = (Image)image.Image.Clone(); pictureBox2.Image = (Image)image.Image.Clone(); //setImageProperties(); //fileOpened = true; } }
public static string GetWidthAndHeight(string filename) { string result; using (var imageFactory = new ImageFactory()) { var image = imageFactory .Load(filename) .Image; result = image.Width + " x " + image.Height; } return result; }
public byte[] ResizeImage(byte[] imageBytes, int width, int height) { var size = new Size(width, height); using (var inStream = new MemoryStream(imageBytes)) using (var outStream = new MemoryStream()) using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(inStream) .Resize(size) .Save(outStream); return outStream.ToArray(); } }
/// <summary> /// 上传图片 /// </summary> /// <returns></returns> public async Task<IHttpActionResult> Post() { try { string fileName = Guid.NewGuid().ToString(); string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg"); string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg"); System.Drawing.Bitmap image = new System.Drawing.Bitmap(HttpContext.Current.Request.InputStream); image.Save(fileOrginalFile); using (var imageFactory = new ImageFactory(preserveExifData: true)) { System.Drawing.Size size = new System.Drawing.Size(800, 1600); ResizeLayer resize = new ResizeLayer(size, ResizeMode.Max); imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized800Name); } OSSHelper blob = new OSSHelper(AIHE.WebApi.Helpers.UtilityString.BlobString.YiQiHeHe); // BlobHelper blob = new BlobHelper(BlobString.Portrait); string contentType = "image/jpeg"; blob.UploadFile(fileResized800Name, fileName, contentType); //删除文件 File.Delete(fileOrginalFile); File.Delete(fileResized800Name); return Json(new ResponseMessageModel(new { ImageName = fileName, ImageUrl = CacheObjectHelper.SystemConfig.url_blob + fileName })); } catch (Exception ex) { return Json(new { Code = 10, Message = "上传失败" }); } }
/// <summary> /// Process an individual request. /// </summary> /// <param name="context">OWIN context.</param> /// <returns>Returns next middleware.</returns> public async override Task Invoke(IOwinContext context) { string imageFilePath = HostingEnvironment.MapPath("~" + context.Request.Path.Value); // Check for the correct folder and image existance if (!context.Request.Path.StartsWithSegments(this._options.Folder) || string.IsNullOrEmpty(imageFilePath) || !File.Exists(imageFilePath)) { await this.Next.Invoke(context); return; } // Check for the watermark image existance string watermarkFilePath = HostingEnvironment.MapPath("~" + this._options.Watermark.Value); if (string.IsNullOrEmpty(watermarkFilePath) || !File.Exists(watermarkFilePath)) { throw new FileNotFoundException("Watermark image was not found.", this._options.Watermark.Value); } // Read a file and resize it. using (var imageStream = new MemoryStream(File.ReadAllBytes(imageFilePath))) { using (var waterMarkImage = Image.FromFile(watermarkFilePath)) { using (var outStream = new MemoryStream()) { using (var factory = new ImageFactory()) { // Load, resize, set the format and quality and save an image. factory.Load(imageStream) //.Resize(new Size(150, 0)) .Format(new JpegFormat()) .Quality(100) .Overlay(new ImageLayer() { Image = waterMarkImage, Opacity = this._options.Opacity }) .Save(outStream); } context.Response.Write(outStream.ToArray()); } } } context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "image/jpg"; }
private void CustomSearchImplementationOne_Load(object sender, EventArgs e) { this.Left = slidingBarWidthTakenIn; this.Height = Screen.PrimaryScreen.WorkingArea.Height; this.Top = 0; this.Width = Screen.PrimaryScreen.WorkingArea.Width - slidingBarWidthTakenIn; ImageFactory imgfBack = new ImageFactory(); imgfBack.Load(@"C:\ProjectSnowshoes\System\Media\blackBackSearch.png"); imgfBack.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); this.BackgroundImage = imgfBack.Image; }
private byte[] GenerateThumbnail(byte[] image) { using (MemoryStream inStream = new MemoryStream(image), outStream = new MemoryStream()) { using (var fac = new ImageFactory()) { fac.Load(inStream) .Resize(new ResizeLayer(new Size(180, 180), ResizeMode.Max)) .Format(new JpegFormat()) .Quality(90) .Save(outStream); } return outStream.ToArray(); } }
public static void Main(string[] args) { const string InputImages = @"..\..\..\ImageProcessor.UnitTests\Images\"; const string OutputImages = @"..\..\images\output"; string root = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath; string inPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(root), InputImages)); string outPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(root), OutputImages)); DirectoryInfo di = new DirectoryInfo(inPath); IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".jpg", ".jpeg", ".jfif", ".gif", ".bmp", ".png", ".tif"); foreach (FileInfo fileInfo in files) { // Start timing. byte[] photoBytes = File.ReadAllBytes(fileInfo.FullName); Console.WriteLine("Processing: " + fileInfo.Name); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); using (MemoryStream inStream = new MemoryStream(photoBytes)) using (ImageFactory imageFactory = new ImageFactory(true, true)) { Size size = new Size(50, 0); ResizeLayer layer = new ResizeLayer(size); imageFactory.Load(inStream) .Resize(layer) //.Resolution(400, 400) //.ReplaceColor(Color.LightGray, Color.Yellow, 10) .Save(Path.GetFullPath(Path.Combine(outPath, fileInfo.Name))); stopwatch.Stop(); } // Report back. long peakWorkingSet64 = Process.GetCurrentProcess().PeakWorkingSet64; float mB = peakWorkingSet64 / (float)1024 / 1024; Console.WriteLine(@"Completed {0} in {1:s\.fff} secs {2}Peak memory usage was {3} bytes or {4} Mb.", fileInfo.Name, stopwatch.Elapsed, Environment.NewLine, peakWorkingSet64.ToString("#,#"), mB); } Console.ReadLine(); }
public static string GetThumbnailFromFullSizeImg(string filename) { var thumbnailPath = StoragePath.GetPath("thumbnail-" + DateTime.Now.GetHashCode() + "-" + Guid.NewGuid().ToString().Substring(0, 7)); using (var imageFactory = new ImageFactory()) { var image = imageFactory .Load(filename) .Image; var ratio = (float) image.Width / image.Height; image = imageFactory .Resize(new Size((int)(ThumbnailHeight * ratio), ThumbnailHeight)) .Image; image.Save(thumbnailPath); } return thumbnailPath; }
public void ExtractArchive() { var archive = ArchiveFactory.Open(filepath); temp_dir = GetTemporaryDirectory(); foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { string ek = entry.Key.ToLower(); if (entry.Key.ToLower().StartsWith("zz")) { continue; } file_base = Path.GetFileNameWithoutExtension(entry.Key); MemoryStream memStream = new MemoryStream(); entry.WriteTo(memStream); //Page temp_page = new Page(memStream, entry.Key); //orig_pages.Add(temp_page); ISupportedImageFormat format = new WebPFormat { Quality = 80 }; ImageFactory image = new ImageProcessor.ImageFactory(); try { image.Load(memStream.ToArray()) .Format(format) .Save(converted); } catch { continue; } string filename = Path.Combine(temp_dir, file_base + ".webp"); using (System.IO.FileStream output = new System.IO.FileStream(filename, FileMode.Create)) { converted.CopyTo(output); memStream.Dispose(); output.Close(); } } } CompressArchive(); }
public static CalorieImage ProcessImage(MemoryStream Input) { var NewImg = new CalorieImage(); ISupportedImageFormat format = new PngFormat { Quality = 99 }; //image using (MemoryStream maxStream = new MemoryStream()) { var RL = new ImageProcessor.Imaging.ResizeLayer(new Size(500, 500), ImageProcessor.Imaging.ResizeMode.Pad) {Upscale = false}; using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false)) { imageFactory.Load(Input).Resize(RL) .Format(format) .BackgroundColor(Color.Transparent) .Save(maxStream); } NewImg.ImageData = maxStream.ToArray(); } //thumbnail using (MemoryStream thumbStream = new MemoryStream()) { var RL = new ImageProcessor.Imaging.ResizeLayer(new Size(100, 100), ImageProcessor.Imaging.ResizeMode.Pad) {Upscale = false}; using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false)) { imageFactory.Load(Input).Resize(RL) .Format(format) .BackgroundColor(Color.Transparent) .Save(thumbStream); } NewImg.ThumbData= thumbStream.ToArray(); } return NewImg; }
public void Resize() { byte[] imgBytes = File.ReadAllBytes(Path.FullName); using(MemoryStream inStream = new MemoryStream(imgBytes)) { using(MemoryStream outStream = new MemoryStream()) { using(ImageFactory factory = new ImageFactory(true)) { ResizeLayer resizeLayer = new ResizeLayer(NewSize); resizeLayer.ResizeMode = ResizeMode.Stretch; factory.Load(inStream).Resize(resizeLayer).Save(outStream); } SaveFile(outStream); } } OnImageResized(); }
private string SaveLargeImage(byte[] bytes, string fileName) { using (MemoryStream inStream = new MemoryStream(bytes)) { using (MemoryStream outStream = new MemoryStream()) { using (ImageFactory imageFactory = new ImageFactory()) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream); int width = imageFactory.Image.Size.Width; int height = imageFactory.Image.Size.Height; if (width > 1600) { int newHeight = (int)((1600 / (double)width) * height); imageFactory.Resize(new Size(1600, newHeight)); imageFactory.Format(ImageFormat.Jpeg); imageFactory.Quality(80); imageFactory.Save(outStream); } else if (height > 1600) { int newWidth = (int)((1600 / (double)height) * width); imageFactory.Resize(new Size(newWidth, 1600)); imageFactory.Format(ImageFormat.Jpeg); imageFactory.Quality(80); imageFactory.Save(outStream); } else { imageFactory.Save(outStream); } } outStream.Position = 0; var resizedResult = this._fileStorage.UploadFile(outStream, fileName, "products/"); return resizedResult.Uri.ToString(); } } }
public byte[] CreatePreview(Stream stream, MediaTypes mediaType, Size size) { byte[] result; var format = mediaType.DetectFormat(); var resizeLayer = new ResizeLayer(size, ResizeMode.Crop); stream.ResetStream(); using (var outStream = new MemoryStream()) { using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(stream) .Format(format) .Resize(resizeLayer) .Save(outStream); } result = outStream.ToArray(); } return result; }
public byte[] CropImage(Stream stream, MediaTypes mediaType, Rectangle rectangle) { byte[] result; var format = mediaType.DetectFormat(); stream.ResetStream(); using (var outStream = new MemoryStream()) { using (var imageFactory = new ImageFactory()) { imageFactory.Load(stream) .Format(format) .Crop(rectangle) .Save(outStream); } result = outStream.ToArray(); } return result; }
public static string DownloadImageAndResize(string image) { try { using (var imageFactory = new ImageFactory(true)) { using (var stream = new MemoryStream()) { imageFactory.Load(DownloadData(image)) .Resize(new ResizeLayer(new Size(800, 800), ResizeMode.Max)) .Format(new PngFormat()) .Save(stream); var fileName = Path.GetFileNameWithoutExtension(image) + ".png"; var url = UploadFileToDirectory(stream, "Products", fileName); return url; } } } catch (Exception) { return string.Empty; } }
private static byte[] GetandResizeImage(string filePath) { var size = new Size(1024, 683);//RM Spec states 3:2 ratio max size 1024 var format = new JpegFormat { Quality = 90 }; using (var webClient = new WebClient()) { using (MemoryStream inStream = new MemoryStream(webClient.DownloadData(filePath)), outStream = new MemoryStream()) { using (var imageFactory = new ImageFactory()) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream) .BackgroundColor(Color.White) .Resize(size) .Format(format) .Save(outStream); } return outStream.ToArray(); } } }
private Stream ProcessImage(IDocument input, ISupportedImageFormat format, ImageInstruction ins) { using (var imageFactory = new img.ImageFactory(preserveExifData: true)) { // Load, resize, set the format and quality and save an image. img.ImageFactory fac; using (Stream stream = input.GetStream()) { fac = imageFactory.Load(stream).Format(format); } if (ins.IsNeedResize) { if (ins.IsCropRequired) { var layer = new ResizeLayer( size: ins.GetCropSize().Value, anchorPosition: ins.GetAnchorPosition(), resizeMode: ResizeMode.Crop ); fac.Resize(layer); } else { fac.Resize(ins.GetCropSize().Value); } } foreach (var f in ins.Filters) { fac.Filter(ins.GetMatrixFilter(f)); } if (ins.Brightness.HasValue) { fac.Brightness(ins.Brightness.Value); } if (ins.Constraint.HasValue) { fac.Constrain(ins.Constraint.Value); } if (ins.Opacity.HasValue) { fac.Alpha(ins.Opacity.Value); } if (ins.Hue != null) { fac.Hue(ins.Hue.Degrees, ins.Hue.Rotate); } if (ins.Tint != null) { fac.Tint(ins.Tint.Value); } if (ins.Vignette != null) { fac.Vignette(ins.Vignette.Value); } if (ins.Saturation.HasValue) { fac.Saturation(ins.Saturation.Value); } if (ins.Contrast.HasValue) { fac.Contrast(ins.Contrast.Value); } var outputStream = new MemoryStream(); fac.Save(outputStream); outputStream.Seek(0, SeekOrigin.Begin); return(outputStream); } }
private void goGenerateProcessesFriendship() { int artOfficial = 0; foreach (var theProcess in Process.GetProcesses()) { // hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Center; if (theProcess.MainWindowTitle != "" && theProcess.MainWindowTitle != "Space") { artOfficial++; } } if (artOfficial != currentCountProc) { spaceForProcesses.Controls.Clear(); foreach (var theProcess in Process.GetProcesses()) { Label hmGreatJobFantasticAmazing = new Label(); if (theProcess.MainWindowTitle != "" && theProcess.MainWindowTitle != "Space") { //hmGreatJobFantasticAmazing.Text = theProcess.MainWindowTitle; hmGreatJobFantasticAmazing.Margin = new Padding(6, 0, 6, 0); hmGreatJobFantasticAmazing.Visible = true; // hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 13, FontStyle.Italic); Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap().Save(@"C:\ProjectSnowshoes\temptaskico.png"); /*DualImageForm thanksVKLines = new DualImageForm(); thanksVKLines.pic = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); thanksVKLines.analyze(); thanksVKLines.pic2.Save(@"C:\ProjectSnowshoes\newtemptaskico.png");*/ ImageFactory grayify = new ImageFactory(); grayify.Load(@"C:\ProjectSnowshoes\temptaskico.png"); //grayify.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); //grayify.Tint(Color.FromName("Gray")); hmGreatJobFantasticAmazing.Image = grayify.Image; hmGreatJobFantasticAmazing.Click += (sender, args) => { //System.Diagnostics.Process.Start(theProcess.Modules[0].FileName); SwitchToThisWindow(theProcess.MainWindowHandle, false); }; hmGreatJobFantasticAmazing.MouseHover += (sender, args) => { Properties.Settings.Default.stayHere = true; Properties.Settings.Default.Save(); int recordNao = hmGreatJobFantasticAmazing.Left; hmGreatJobFantasticAmazing.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); // Yeahhhhhhhhh I'm going to have to do this another way // panel1.Controls.Add(areYouSeriouslyStillDoingThisLetItGo); // Oh // I can just make another form to draw over and go have turnips with parameters // Also credits to Microsoft Word's "Sentence Case" option as this came out in all caps originally //Measuring string turnt-up-edness was guided by an answer on Stack Overflow by Tom Anderson. String keepThisShortWeNeedToOptimize = Process.GetProcessById(theProcess.Id).MainWindowTitle; Graphics heyGuessWhatGraphicsYeahThatsRight = Graphics.FromImage(new Bitmap(1, 1)); SizeF sure = heyGuessWhatGraphicsYeahThatsRight.MeasureString(keepThisShortWeNeedToOptimize, new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular, GraphicsUnit.Point)); Size sureAgain = sure.ToSize(); int recordThatJim; if (sureAgain.Width >= 300) { recordThatJim = sureAgain.Width + 10; } else { recordThatJim = 300; } CanWeMakeAHoverFormLikeThisIsThisLegal notAsLongInstanceName = new CanWeMakeAHoverFormLikeThisIsThisLegal(recordNao + 150, bottomPanel.Height, recordThatJim, keepThisShortWeNeedToOptimize); notAsLongInstanceName.Show(); notAsLongInstanceName.BringToFront(); //hmGreatJobFantasticAmazing.BringToFront(); //panel1.Controls.Add(hmGreatJobFantasticAmazing); //hmGreatJobFantasticAmazing.Top = bottomPanel.Top - 40; //hmGreatJobFantasticAmazing.Left = recordNao + 150; //hmGreatJobFantasticAmazing.BringToFront(); //hmGreatJobFantasticAmazing.Invalidate(); /*hmGreatJobFantasticAmazing.Height = 100; hmGreatJobFantasticAmazing.Width = 100;*/ }; hmGreatJobFantasticAmazing.MouseLeave += (sender, args) => { /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleCenter; hmGreatJobFantasticAmazing.AutoEllipsis = false; hmGreatJobFantasticAmazing.Width = 40; hmGreatJobFantasticAmazing.BackColor = Color.Transparent; //hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); //hmGreatJobFantasticAmazing.ForeColor = Color.White; hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft; hmGreatJobFantasticAmazing.Text = "";*/ try { Application.OpenForms["CanWeMakeAHoverFormLikeThisIsThisLegal"].Close(); } catch (Exception exTurnip) { } hmGreatJobFantasticAmazing.BackColor = Color.Transparent; hmGreatJobFantasticAmazing.Invalidate(); Properties.Settings.Default.stayHere = false; Properties.Settings.Default.Save(); }; //openFileToolTip.SetToolTip(hmGreatJobFantasticAmazing, theProcess.MainWindowTitle); //hmGreatJobFantasticAmazing.BackgroundImage = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); hmGreatJobFantasticAmazing.Height = bottomPanel.Height; hmGreatJobFantasticAmazing.Width = 50; spaceForProcesses.Controls.Add(hmGreatJobFantasticAmazing); hmGreatJobFantasticAmazing.Invalidate(); }} } currentCountProc = artOfficial; }
public async Task<IHttpActionResult> Post() { string itemid=HttpContext.Current.Request.Form["itemid"]; string fileName = Guid.NewGuid().ToString(); // 检查是否是 multipart/form-data //if (!Request.Content.IsMimeMultipartContent("form-data")) //{ // return Json(new // { // Code = 20000, // Detail = new // { // Description = "没有文件" // } // }); //} // Stream img = Request.Content.ReadAsStreamAsync(); try { string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/Orignal/" + fileName + ".jpg"); string fileResized150Name = HttpContext.Current.Server.MapPath("~/MyUpload/Resize150/" + fileName + ".jpg"); string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/Resize800/" + fileName + ".jpg"); // HttpContext.Current.Request.Files[0].SaveAs(fileOrginalFile); System.Drawing.Bitmap image = new System.Drawing.Bitmap(HttpContext.Current.Request.InputStream); image.Save(fileOrginalFile); using (var imageFactory = new ImageFactory(preserveExifData: true)) { System.Drawing.Size size = new System.Drawing.Size(200, 200); imageFactory.Load(fileOrginalFile).Resize(size).Save(fileResized150Name); size = new System.Drawing.Size(800, 1600); ResizeLayer resize = new ResizeLayer(size, ResizeMode.Max); imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized800Name); } BlobHelper blob = new BlobHelper(BlobString.Portrait); string contentType = "image/jpeg"; await blob.UploadFile(fileResized150Name, fileName, contentType); await blob.UploadFile(fileResized800Name, fileName + "-big", contentType); //删除文件 File.Delete(fileOrginalFile); File.Delete(fileResized150Name); File.Delete(fileResized800Name); return Json(new { Code = 10000, Detail = "http://hdy.awblob.com/portrait/" + fileName }); } catch (Exception ex) { return Json(new { Code = 10, Message="上传失败" }); } }
private static MemoryStream MakeBlackWhite(MemoryStream inStream) { var outStream = new MemoryStream(); // Initialize the ImageFactory using the overload to preserve EXIF metadata. using (var imageFactory = new ImageFactory(preserveExifData: true)) { // Load, resize, set the format and quality and save an image. imageFactory.Load(inStream.ToArray()) .Filter(MatrixFilters.BlackWhite) .Save(outStream); } return outStream; }
private void CaptureLayer() { SetFlashFill(captureIndex); flashStoryboard.Begin(this); switch (captureIndex) { case 0: capture1Storyboard.Begin(this); break; case 1: capture2Storyboard.Begin(this); break; case 2: capture3Storyboard.Begin(this); break; default: break; } RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)CompositeImage.ActualWidth, (int)CompositeImage.ActualHeight, 96.0, 96.0, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush brush = new VisualBrush(CompositeImage); dc.DrawRectangle(brush, null, new Rect(new System.Windows.Point(), new System.Windows.Size(CompositeImage.ActualWidth, CompositeImage.ActualHeight))); } renderBitmap.Render(dv); byte[] encoded; using (MemoryStream stream = new MemoryStream()) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(stream); encoded = stream.ToArray(); } BitmapImage processed = new BitmapImage(); double opacity = 1; using (MemoryStream stream = new MemoryStream()) { using (ImageProcessor.ImageFactory imageFactory = new ImageProcessor.ImageFactory(false)) { imageFactory.Load(encoded); imageFactory.Filter(ImageProcessor.Imaging.Filters.Photo.MatrixFilters.BlackWhite); switch (captureIndex) { case 0: break; case 1: imageFactory.Tint(System.Drawing.Color.Magenta); opacity = .4; break; case 2: imageFactory.Tint(System.Drawing.Color.Cyan); opacity = .3; break; case 3: imageFactory.Tint(System.Drawing.Color.Yellow); opacity = .2; break; default: break; } imageFactory.Save(stream); } processed.BeginInit(); processed.CacheOption = BitmapCacheOption.OnLoad; processed.StreamSource = stream; processed.EndInit(); } System.Windows.Controls.Image image = new System.Windows.Controls.Image() { Source = processed, Stretch = Stretch.None, Opacity = opacity }; CompositeLayers.Children.Add(image); }