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; } }
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) { AnimationProcessMode = AnimationProcessMode.All }) { Size size = new Size(50, 0); ResizeLayer layer = new ResizeLayer(size); try { imageFactory.Load(inStream) .BitDepth(1) //.Resize(size) //.Format(new GifFormat()) //.Resolution(400, 400) //.ReplaceColor(Color.LightGray, Color.Yellow, 10) .Save(Path.GetFullPath(Path.Combine(outPath, fileInfo.Name))); } catch (Exception ex) { Console.WriteLine(ex.Message); } stopwatch.Stop(); // trans.gif says it's (0, 0, 0, 0) but the image saves as black. // Color first = ((Bitmap)imageFactory.Image).GetPixel(0, 0); } // 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(); }
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> /// 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 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; }
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; }
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(); } } }); }
static void Main(string[] args) { Console.WriteLine("create slides from input folder image..."); Console.WriteLine("Downloading Music, add credits for http://www.bensound.com/"); Directory.CreateDirectory(TempFolder); var listFile = AssemblyDirectory + "/" + ListFile; File.WriteAllText(listFile, string.Empty); var rand = new Random(DateTime.Now.Millisecond); // Create a new WebClient instance. var myWebClient = new WebClient(); myWebClient.DownloadFile(MusicUrls[rand.Next(0, MusicUrls.Count)], AssemblyDirectory + "/" + TempFolder + "/music.mp3"); for (int i = 0; i < 6; i++) { File.AppendAllText(listFile, string.Format("file '{0}/music.mp3'\r\n", TempFolder)); } var combineMusicParams = string.Format("-y -f concat -i \"{0}\" -c copy \"{1}/musicShuffled.mp3\"", listFile, TempFolder); StartFfmpeg(combineMusicParams, 20); File.WriteAllText(listFile, string.Empty); var files = Directory.GetFiles(AssemblyDirectory + "/input"); //first resize images var imgFactory = new ImageFactory(); var index = 1; foreach (var file in files) { imgFactory.Load(file).Resize(new Size(VideoWidth, VideoHeight)).Save(file); //Console.WriteLine(file); var firstArgs = string.Format("-y -framerate 1/{2} -i \"{0}\" -c:v libx264 -r 30 -pix_fmt yuv420p \"{3}/out{1}.mp4\"", file, index, SecondsPerImage, TempFolder); var secondArgs = string.Format("-y -i \"{3}/out{0}.mp4\" -y -vf fade=in:0:{2} \"{3}/out{1}.mp4\"", index, index + 1, 30 * FadePercentage / 100, TempFolder); var thirdArgs = string.Format("-y -i \"{4}/out{0}.mp4\" -y -vf fade=out:{3}:{2} \"{4}/out{1}.mp4\"", index + 1, index + 2, 30 * FadePercentage / 100, SecondsPerImage * 30 - 30 * FadePercentage / 100, TempFolder); StartFfmpeg(firstArgs); StartFfmpeg(secondArgs); StartFfmpeg(thirdArgs); File.AppendAllText(listFile, string.Format("file '{1}/out{0}.mp4'\r\n", index + 2, TempFolder)); index += 3; } //ffmpeg -f concat -i mylist.txt -c copy output.mp4 var combineParams = string.Format("-y -f concat -i \"{0}\" -c copy \"{1}/output.mp4\"", listFile, TempFolder); StartFfmpeg(combineParams, 5); //index*SecondsPerImage/3 secs SecondsPerImage secs; var videoSeconds = index * SecondsPerImage / 3; var audioFadeOutParams = string.Format("-y -i \"{2}/musicShuffled.mp3\" -af afade=t=out:st={0}:d={1} \"{2}/audio.mp3\"", videoSeconds - SecondsPerImage * 2, SecondsPerImage * 2 - 1, TempFolder); StartFfmpeg(audioFadeOutParams, 15); var audioParams = string.Format("-y -i \"{0}/output.mp4\" -i \"{0}/audio.mp3\" -shortest outputwaudio.mp4", TempFolder); StartFfmpeg(audioParams, 15); Directory.Delete(TempFolder, true); Console.WriteLine("\r\nREADY!\r\n"); Console.ReadLine(); }
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; } }
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> /// 上传图片 /// </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 = "上传失败" }); } }
public ImageMan() { try { imFactory = new ImageFactory(preserveExifData: true); original = true; } catch (Exception ex) { } }
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; }
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 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 Image() { this.AvailableMessageBytes = 0; this.AvailableMessageCharacters = 0; this.BytesPerPixel = 0; this.CharacterEncoding = Encoding.UTF8; this.EncodedBits = BitsToEncode.One; this.SourceImage = null; this.ImageDataLength = 0; this.ImagePixels = 0; this.PixelFormat = System.Drawing.Imaging.PixelFormat.DontCare; this.IsImageLoaded = false; this.MessagePosition = 0; this.EndOfMessageReached = false; }
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(200, 200); ResizeLayer layer = new ResizeLayer(size); imageFactory.Load(inStream) .Resize(layer) .Resolution(400, 400) .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 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 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 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[] 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 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; }
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 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); }