public bool TryGetContentType(IFormatInfo originalFormat, HttpRequestBase request, IFormatInfoProvider formatInfoProvider, out IFormatInfo transformedFormat, out BitmapEncoder encoder) { var format = request.QueryString["format"]; if (string.IsNullOrEmpty(format)) { format = originalFormat.Extension.Substring(1); } switch (format.ToLower()) { case "jpg": int quality; if (!int.TryParse(request.QueryString["quality"], out quality) || quality <= 0 || quality > 100) { quality = 80; } transformedFormat = formatInfoProvider.ResolveFromExtension(".jpg"); encoder = new JpegBitmapEncoder { QualityLevel = quality }; return transformedFormat != null; case "png": transformedFormat = formatInfoProvider.ResolveFromExtension(".png"); encoder = new PngBitmapEncoder(); return transformedFormat != null; default: transformedFormat = null; encoder = null; return false; } }
private static byte[] GetImage(UIElement source, BitmapEncoder bitmapEncoder, double scale) { double actualHeight = source.RenderSize.Height; double actualWidth = source.RenderSize.Width; double renderHeight = actualHeight * scale; double renderWidth = actualWidth * scale; var renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(source); var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTarget.Render(drawingVisual); bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget)); Byte[] imageArray; using (var outputStream = new MemoryStream()) { bitmapEncoder.Save(outputStream); imageArray = outputStream.ToArray(); } return imageArray; }
public Task<bool> SendMail(string sendToEmail, BitmapEncoder bitmap) { bool returnValue = true; MailMessage msg = new MailMessage("*****@*****.**", sendToEmail, "Your Microsoft Kinect Photo Booth Picture", body); msg.BodyEncoding = System.Text.Encoding.Unicode; msg.IsBodyHtml = true; ContentType ct = new ContentType(); ct.MediaType = MediaTypeNames.Image.Jpeg; ct.Name = "MSKinectPhotobooth.png"; MemoryStream stream = new MemoryStream(); bitmap.Save(stream); stream.Position = 0; Attachment data = new Attachment(stream, "MSPhotobooth.png"); msg.Attachments.Add(data); Task<bool> t = new Task<bool>(() => { try { //SmtpClient smtpClient = new SmtpClient("smtp.office365.com") SmtpClient smtpClient = new SmtpClient(_SMTPEmailServer) { UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(_SMTPEmailUserID, _SMTPEmailPassword), }; smtpClient.Send(msg); smtpClient.Dispose(); } catch (Exception ex) { returnValue = false; } finally { msg.Dispose(); } return returnValue; }); t.Start(); return t; }
public static void Save(FrameworkElement visual, Stream stream, BitmapEncoder encoder) { RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32); bitmap.Render(visual); BitmapFrame frame = BitmapFrame.Create(bitmap); encoder.Frames.Add(frame); encoder.Save(stream); }
public static void Save(this BitmapSource bitmap, string path, BitmapEncoder encoder) { using (var fs = File.OpenWrite(path)) { encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(fs); } }
private void SaveUsingEncoder(BitmapEncoder encoder) { encoder.Frames.Add(BitmapFrame.Create(this.imageToSave)); using (var stream = File.Create(this.fileName)) { encoder.Save(stream); } }
public void Save() { bitmapEncoder = GetBitmapEncoder(Path.GetExtension(fileName)); if (bitmapEncoder != null) SaveAsBitmapFile(); else SaveAsMyPaintFile(); }
private static void Save(string fileName, BitmapEncoder encoder, BitmapSource source) { BitmapFrame outputFrame = BitmapFrame.Create(source); encoder.Frames.Add(outputFrame); using (FileStream file = File.OpenWrite(fileName)) { encoder.Save(file); } }
public void Capture(string filePath, BitmapEncoder encoder) { var bmp = new RenderTargetBitmap((int) Width, (int) Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(this); encoder.Frames.Add(BitmapFrame.Create(bmp)); using (Stream stm = File.Create(filePath)) { encoder.Save(stm); } }
/// <summary> /// The encode bitmap. /// </summary> /// <param name="bitmapEncoder"> /// The bitmap encoder. /// </param> /// <param name="bitmap"> /// The bitmap. /// </param> /// <returns> /// </returns> private static byte[] EncodeBitmap(BitmapEncoder bitmapEncoder, Bitmap bitmap) { BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); using (var ms = new MemoryStream()) { bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource)); bitmapEncoder.Save(ms); return ms.ToArray(); } }
private static void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder) { var renderTargetBitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 100, 100, PixelFormats.Pbgra32); System.Console.WriteLine((int)visual.ActualWidth + "\n" + (int)visual.ActualHeight); renderTargetBitmap.Render(visual); var bitmapFrame = BitmapFrame.Create(renderTargetBitmap); encoder.Frames.Add(bitmapFrame); using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate)) { encoder.Save(fileStream); } }
public static void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder) { RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32); bitmap.Render(visual); BitmapFrame frame = BitmapFrame.Create(bitmap); encoder.Frames.Add(frame); using (var stream = File.Create(fileName)) { encoder.Save(stream); } }
/// <summary> /// Saves the given canvas using the given bitmap encoder. /// </summary> /// <param name="Canvas">The canvas.</param> /// <param name="BitmapEncoder">A bitmap encoder.</param> /// <param name="dpiX">The desired x-resolution of the saved image.</param> /// <param name="dpiY">The desired y-resolution of the saved image.</param> /// <returns>A memory stream containing the encoded JPEG image.</returns> public static MemoryStream SaveAs(this Canvas Canvas, BitmapEncoder BitmapEncoder, Double dpiX = 96d, Double dpiY = 96d) { #region Initial checks if (Canvas == null) throw new ArgumentNullException("The given canvas must not be null!"); if (BitmapEncoder == null) throw new ArgumentNullException("The bitmap encoder must not be null!"); #endregion // Save and reset current canvas transform var CanvasTransformation = Canvas.LayoutTransform; Canvas.LayoutTransform = null; // Measure and arrange the canvas var CanvasWidth = Double.IsNaN(Canvas.Width) ? Canvas.ActualWidth : Canvas.Width; var CanvasHeight = Double.IsNaN(Canvas.Height) ? Canvas.ActualHeight : Canvas.Height; var CanvasSize = new Size(CanvasWidth, CanvasHeight); Canvas.Measure(CanvasSize); Canvas.Arrange(new Rect(CanvasSize)); var _RenderTargetBitmap = new RenderTargetBitmap( (Int32) (CanvasSize.Width * dpiX / 96.0), (Int32) (CanvasSize.Height * dpiY / 96.0), dpiX, dpiY, PixelFormats.Pbgra32); _RenderTargetBitmap.Render(Canvas); // Encode bitmap var MemoryStream = new MemoryStream(); BitmapEncoder.Frames.Add(BitmapFrame.Create(_RenderTargetBitmap)); BitmapEncoder.Save(MemoryStream); // Restore previously saved layout Canvas.LayoutTransform = CanvasTransformation; return MemoryStream; }
private void Window_Loaded(object sender, RoutedEventArgs e) { radioButton1.IsChecked = false; this.fileNameTextBox.Text = "C:\\Output\\test"; // Create the drawing group we'll use for drawing this.drawingGroup = new DrawingGroup(); this._imEncoder = new PngBitmapEncoder(); // Create an image source that we can use in our image control this.imageSource = new DrawingImage(this.drawingGroup); this._frameList = new List<System.Drawing.Bitmap>(); this._frameTimes = new List<float>(); // Display the drawing using our image control skeletonImage.Source = this.imageSource; if (KinectSensor.KinectSensors.Count > 0) { _sensor = KinectSensor.KinectSensors[0]; if (_sensor.Status == KinectStatus.Connected) { _sensor.ColorStream.Enable(); _sensor.DepthStream.Enable(); _sensor.SkeletonStream.Enable(); _sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(_sensor_AllFramesReady); _skeletonData = new Skeleton[_sensor.SkeletonStream.FrameSkeletonArrayLength]; _sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(_sensor_SkeletonFrameReady); this.numFramesBox.Text = 0.ToString(); _sensor.Start(); } } }
public ImageMediaTransformer( IEnumerable<Func<BitmapSource, BitmapSource>> bitmapTransformChain, BitmapEncoder encoder, IFormatInfo formatInfo ) { _bitmapTransformChain = bitmapTransformChain; _encoder = encoder; OutputFormat = formatInfo; }
/// <summary> /// Note RenderTargetBitmap has a huge memory leak that was fixed in .NET 4.0 /// but only if you reference Winforms. /// </summary> /// <param name="copyTarget"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="enc"></param> /// <param name="outStream"></param> /// <param name="dpi"></param> /// <returns></returns> public static Stream CopyFrameworkElementToStreamNew(FrameworkElement copyTarget, double width, double height, BitmapEncoder enc, Stream outStream, double dpi) { // Store the Frameworks current layout transform, as this will be restored later Transform storedLayoutTransform = copyTarget.LayoutTransform; Transform storedRenderTransform = copyTarget.RenderTransform; double scale = dpi / 96.0; width *= scale; height *= scale; copyTarget.RenderTransform = new ScaleTransform(scale, scale); // Set the layout transform to unity to get the nominal width and height copyTarget.LayoutTransform = new ScaleTransform(1, 1); copyTarget.UpdateLayout(); RenderTargetBitmap rtb; copyTarget.LayoutTransform = new ScaleTransform(1.0 / scale, 1.0 / scale); copyTarget.UpdateLayout(); // Render to a Bitmap Source, note that the DPI is changed for the // render target as a way of scaling the FrameworkElement rtb = new RenderTargetBitmap( (int)width, (int)height, dpi, dpi, PixelFormats.Default); rtb.Render(copyTarget); // Convert from a WinFX Bitmap Source to a Win32 Bitamp enc.Frames.Add(BitmapFrame.Create(rtb)); enc.Save(outStream); // Restore the Framework Element to it's previous state copyTarget.LayoutTransform = storedLayoutTransform; copyTarget.RenderTransform = storedRenderTransform; copyTarget.UpdateLayout(); return outStream; }
public MemoryStream RenderToImage(float dpiX, float dpiY, Rect rect, BitmapEncoder encoder) { double qualityCoefficient = Math.Floor(4096.0/(Math.Max(rect.Width, rect.Height)*dpiX/25.4)); if (Math.Abs(qualityCoefficient - 0) < GlobalData.Precision) qualityCoefficient = 4096.0/(Math.Max(rect.Width, rect.Height)*dpiX/25.4); var renderTargetBitmap = new RenderTargetBitmap((int)(rect.Width * dpiX / 25.4), (int)(rect.Height * dpiY / 25.4), dpiX * qualityCoefficient, dpiY * qualityCoefficient, PixelFormats.Pbgra32); renderTargetBitmap.Render(this); encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); var stream = new MemoryStream(); encoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); return stream; }
/// <summary> /// Return the list of extensions for a bitmap encoder /// </summary> /// <param name="encoder"></param> /// <returns>List of extensions of the form .jpeg etc.</returns> public static IEnumerable<string> ExtensionsFor(BitmapEncoder encoder) { return encoder.CodecInfo.FileExtensions.Split(','); }
/// <summary> /// Copies a framework element to a bitmap stored in a memory stream /// </summary> /// <param name="copyTarget"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="enc"></param> /// <param name="str"></param> /// <returns></returns> public static void CopyFrameworkElementToStream(FrameworkElement copyTarget, double width, double height, BitmapEncoder enc, Stream str) { // Store the Frameworks current layout transform, as this will be restored later Transform storedTransform = copyTarget.LayoutTransform; // Set the layout transform to unity to get the nominal width and height copyTarget.LayoutTransform = new ScaleTransform(1, 1); copyTarget.UpdateLayout(); double baseHeight = copyTarget.ActualHeight; double baseWidth = copyTarget.ActualWidth; // Now scale the layout to fit the bitmap copyTarget.LayoutTransform = new ScaleTransform(baseWidth / width, baseHeight / height); copyTarget.UpdateLayout(); // Render to a Bitmap Source, note that the DPI is changed for the // render target as a way of scaling the FrameworkElement RenderTargetBitmap rtb = new RenderTargetBitmap( (int)width, (int)height, 96d * width / baseWidth, 96d * height / baseHeight, PixelFormats.Default); rtb.Render(copyTarget); // Convert from a WPF Bitmap Source to a Win32 Bitamp enc.Frames.Add(BitmapFrame.Create(rtb)); enc.Save(str); // Restore the Framework Element to it's previous state copyTarget.LayoutTransform = storedTransform; copyTarget.UpdateLayout(); }
//倒數後拍照 void timer_Tick(object sender, EventArgs e) { if (sec > 0) { sec--; showtime.Text = "打扮美美的唷!! 倒數 " + sec.ToString() + " 秒 "; //timerText是介面上的一個TextBlock if (sec < 4) { showtime.Text = "要拍照囉!! 倒數 " + sec.ToString() + " 秒 "; ; //timerText是介面上的一個TextBlock } } else { timer.Stop(); showtime.Text = "拍照完成囉!! "; btnSquare.Visibility = Visibility.Visible; btnCircle.Visibility = Visibility.Visible; btnTakePic.Visibility = Visibility.Visible; btnPreview.Visibility = Visibility.Visible; btnSave.Visibility = Visibility.Visible; //拍照聲音 //sound.Play(); //System.Media.SystemSounds.Beep.Play(); //系統聲音 //拍照 if (null == this.sensorChooser || null == this.sensorChooser.Kinect) { this.statusBarText.Text = Properties.Resources.ConnectDeviceFirst; return; } int colorWidth = this.foregroundBitmap.PixelWidth; int colorHeight = this.foregroundBitmap.PixelHeight; // create a render target that we'll render our controls to // 新增一個影像與背景合併區 var renderBitmap = new RenderTargetBitmap(colorWidth, colorHeight, 96.0, 96.0, PixelFormats.Pbgra32); var dv = new DrawingVisual();//使用繪圖工具 using (var dc = dv.RenderOpen())//開使繪圖並將影像與背景合繪再一起 { // render the imgBackdrop var backdropBrush = new VisualBrush(imgBackdrop); dc.DrawRectangle(backdropBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight))); // render the color image masked out by players var colorBrush = new VisualBrush(imgMaskedColor); dc.DrawRectangle(colorBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight))); } renderBitmap.Render(dv);//將合併繪圖畫在renderBitmap合併區上 // create a png bitmap encoder which knows how to save a .png file // create frame from the writable bitmap and add to encoder //將renderBitmap合併區轉成png格式 encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); } }
private string SaveResultToFile(string sourcePath, BitmapEncoder encoder) { string destinationPath = _renamer.Rename(sourcePath); if (encoder.GetType() == DefaultEncoderType) { destinationPath = Path.ChangeExtension(destinationPath, DefaultEncoderExtension); } using (var destinationStream = File.Open(destinationPath, FileMode.Create)) { // Save the final image encoder.Save(destinationStream); } return destinationPath; }
public static void Save(this BitmapSource bitmapSource, IO.Stream stream, BitmapEncoder encoder) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(stream); stream.Flush(); }
private static byte[] ConvertTo_UsingEncoder(this BitmapSource input, BitmapEncoder encoder) { if (input == null) return null; var stream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(input,null,null,null)); encoder.Save(stream); var serializedImage = stream.ToArray(); stream.Close(); stream.Dispose(); return serializedImage; }
private void GetBitmapDecoderEncoder(string sourcePath, out BitmapDecoder decoder, out BitmapEncoder encoder) { using (var sourceStream = File.OpenRead(sourcePath)) { // NOTE: Using BitmapCacheOption.OnLoad here will read the entire file into // memory which allows us to dispose of the file stream immediately decoder = BitmapDecoder.Create(sourceStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); try { // NOTE: This will throw if the codec does not support encoding var dummy = encoder.CodecInfo; } catch (NotSupportedException) { // Fallback to the default (JPEG) encoder encoder = (BitmapEncoder)Activator.CreateInstance(DefaultEncoderType); } // Set encoder quality if it is a jpeg encoder var jpegEncoder = encoder as JpegBitmapEncoder; if (jpegEncoder != null) { jpegEncoder.QualityLevel = _encoderQualityLevel; } }
bool SaveImage(BitmapEncoder encoder) { string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat); string path = Path.Combine(KissHelper.GetPath(), "kiss-" + time + ".jpg"); try { using (FileStream fs = new FileStream(path, FileMode.Create)) encoder.Save(fs); } catch (IOException) { return false; } return true; }
bool AddVideoFrame(BitmapEncoder encoder) { if (aviStream == null) { Debug.WriteLine("aviStream is null."); return false; } using (MemoryStream s = new MemoryStream()) { encoder.Save(s); Bitmap b = (Bitmap)Image.FromStream(s); aviStream.AddFrame(b); b.Dispose(); } return true; }
public static Stream CopyFrameworkElementToStream(FrameworkElement copyTarget, double width, double height, BitmapEncoder enc, Stream outStream, double? dpi) { if (copyTarget == null) return outStream; // Store the Frameworks current layout transform, as this will be restored later Transform storedTransform = copyTarget.LayoutTransform; // Set the layout transform to unity to get the nominal width and height copyTarget.LayoutTransform = new ScaleTransform(1, 1); copyTarget.UpdateLayout(); double baseHeight = copyTarget.ActualHeight; double baseWidth = copyTarget.ActualWidth; // Now scale the layout to fit the bitmap copyTarget.LayoutTransform = new ScaleTransform(baseWidth/width, baseHeight/height); copyTarget.UpdateLayout(); // Render to a Bitmap Source, the DPI is changed for the // render target as a way of scaling the FrameworkElement var rtb = new RenderTargetBitmap( (int) width, (int) height, 96d*width/baseWidth, 96d*height/baseHeight, PixelFormats.Default); rtb.Render(copyTarget); // Convert from a WinFX Bitmap Source to a Win32 Bitamp if (dpi == null) { enc.Frames.Add(BitmapFrame.Create(rtb)); } else { // Change the DPI var brush = new ImageBrush(BitmapFrame.Create(rtb)); var rtbDpi = new RenderTargetBitmap( (int) width, // PixelWidth (int) height, // PixelHeight (double) dpi, // DpiX (double) dpi, // DpiY PixelFormats.Default); var drawVisual = new DrawingVisual(); using (DrawingContext dc = drawVisual.RenderOpen()) { dc.DrawRectangle(brush, null, new Rect(0, 0, rtbDpi.Width, rtbDpi.Height)); } rtbDpi.Render(drawVisual); enc.Frames.Add(BitmapFrame.Create(rtbDpi)); } enc.Save(outStream); // Restore the Framework Element to it's previous state copyTarget.LayoutTransform = storedTransform; copyTarget.UpdateLayout(); return outStream; }
public async void SendMail(BitmapEncoder bitmap) { if (_email == null) { _email = new EmailService(); } bool mailSent = await _email.SendMail(_EmailAddress, bitmap); }
private void SaveUsingEncoder(System.Windows.Controls.Image image, string fileName, BitmapEncoder encoder) { RenderTargetBitmap rtb = GetTransformedBitmap(image); encoder.Frames.Add(BitmapFrame.Create(rtb)); using (var filestream = new FileStream(fileName, FileMode.Create)) encoder.Save(filestream); }
private static byte[] ImageToBytes(BitmapSource img, BitmapEncoder enc) { MemoryStream memStream = new MemoryStream(); enc.Frames.Add(BitmapFrame.Create(img)); enc.Save(memStream); return memStream.GetBuffer(); }