static public Bitmap toBitmap(BitmapSource bitmapSource) { if (bitmapSource == null) { return(null); } using (MemoryStream stream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapSource)); enc.Save(stream); using (var tempBitmap = new Bitmap(stream)) { // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap." // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream. return(new Bitmap(tempBitmap)); } } }
public void setBackGround() { BitmapImage bitmapImg = PhotoPresent.Singleton.imageContainer.Source as BitmapImage; BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapImg)); System.Drawing.Image img; using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); img = System.Drawing.Image.FromStream(ms); var currentPath = System.Environment.CurrentDirectory; //create directory for wallpaper System.IO.Directory.CreateDirectory(currentPath + "\\backgroundImage\\"); img.Save(currentPath.ToString() + "\\backgroundImage\\background.bmp", System.Drawing.Imaging.ImageFormat.Bmp); SystemParametersInfo(20, 0, currentPath.ToString() + "\\backgroundImage\\background.bmp", 0x2); } }
private void button1_Click(object sender, RoutedEventArgs e) { RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96d, 96d, PixelFormats.Default); rtb.Render(inkCanvas); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); using (FileStream fs = File.Open(NeuralNetwork.Properties.Resources.DrawingFile, FileMode.Create)) { encoder.Save(fs); } Bitmap source1 = new Bitmap(Properties.Resources.DrawingFile); Bitmap bmp = CropImage(source1, new Rectangle(new System.Drawing.Point(10, 10), new System.Drawing.Size((int)inkCanvas.ActualWidth - 10, (int)inkCanvas.ActualHeight - 10))); Bitmap bm = CalculateRectangle(bmp); bm.Save(Properties.Resources.CropedImage); GetPixels(bm); }
public static Bitmap DrawingVisualToBitmap(DrawingVisual visual, Rect rect) { var bmp = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(visual); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); Bitmap bitmap; using (var stream = new MemoryStream()) { encoder.Save(stream); bitmap = new Bitmap(stream); } return(bitmap); }
public static BitmapImage ConvertToBitmapImage(this BitmapSource target) { var bitmapImage = new BitmapImage(); var bitmapEncoder = new BmpBitmapEncoder(); bitmapEncoder.Frames.Add(BitmapFrame.Create(target)); using (var stream = new MemoryStream()) { bitmapEncoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); } return(bitmapImage); }
private void SaveImage() { SaveFileDialog Dialog = new SaveFileDialog(); Dialog.Title = "选择保存位置"; Dialog.Filter = ".bmp|*.bmp"; Dialog.FileName = string.Empty; Dialog.FilterIndex = 1; Dialog.RestoreDirectory = true; if (Dialog.ShowDialog() == false) { return; } string txtFile = Dialog.FileName; var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.img.Source)); using (FileStream stream = new FileStream(txtFile, FileMode.Create)) encoder.Save(stream); }
private void SaveCompressed(object sender, RoutedEventArgs e) { var saveDialog = new SaveFileDialog() { CheckPathExists = true, Filter = "压缩位图文件(*.cbmp)|*.cbmp" }; var result = saveDialog.ShowDialog(); if (result != null && result.Value) { var encoder = new BmpBitmapEncoder(); var destStream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(ViewModel.ImageSource)); encoder.Save(destStream); var imageBytes = destStream.ToArray(); var huffmanFile = new HuffmanFile(imageBytes); huffmanFile.EncodeFile(saveDialog.FileName, saveDialog.FileName + "_key"); } }
public static BitmapImage Crop(this BitmapImage bmp, Int32Rect rct) { CroppedBitmap croppedBmp = new CroppedBitmap(bmp, rct); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); MemoryStream memoryStream = new MemoryStream(); BitmapImage bImg = new BitmapImage(); encoder.Frames.Add(BitmapFrame.Create(croppedBmp)); encoder.Save(memoryStream); bImg.BeginInit(); bImg.CacheOption = BitmapCacheOption.OnLoad; bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); bImg.EndInit(); memoryStream.Close(); return(bImg); }
public static void fn_SaveImage(WriteableBitmap wb, string strPath) { if (wb != null) { try { using (FileStream stream = new FileStream(strPath, FileMode.Create)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(wb)); encoder.Save(stream); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource) { try { System.Drawing.Bitmap bitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapsource)); enc.Save(outStream); outStream.Position = 0; bitmap = new System.Drawing.Bitmap(outStream); } return(bitmap); } catch (Exception) { return(null); } }
/// <summary> /// Saves a <see cref="BitmapSource"/> as a BMP file to the specified location. /// </summary> /// <param name="bitmapSource">The <see cref="BitmapSource"/></param> /// <param name="path">The path to save to.</param> public static void SaveBitmapSourceAsBmp(this BitmapSource bitmapSource, string path) { if (bitmapSource == null) { throw new ArgumentNullException(nameof(bitmapSource)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } Directory.CreateDirectory(Path.GetDirectoryName(path)); using (FileStream fs = new FileStream(path, FileMode.Create)) { BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(fs); } }
/// <summary> /// OOTB support for /Resources/Image.png (as embedded resource), /// or storing the image in the Resources and use the Image overload /// /// For example: GetPicture(/Resources/Image.png) will load the following pack uri /// (assuming your viewmodel is in the MyAddin.Logic assembly) /// pack://application:,,,/MyAddin.Logic;component/Resources/Image.jpg /// </summary> /// <param name="image"></param> /// <returns></returns> public virtual Bitmap GetPicture(string image) { var memoryStream = new MemoryStream(); var bitmap = new Bitmap(memoryStream); if (!image.StartsWith("/")) { image = string.Concat("/", image); } var encoder = new BmpBitmapEncoder(); var packApplicationComponent = string.Format( "pack://application:,,,/{0};component{1}", GetType().Assembly.GetName().Name, image); encoder.Frames.Add(BitmapFrame.Create(new Uri(packApplicationComponent))); encoder.Save(memoryStream); return(bitmap); }
public static void SaveBitmapSourceToFile(BitmapSource imgSrc, string fileName) { if (imgSrc != null) { if (fileName != string.Empty) { using (FileStream stream = new FileStream(fileName, FileMode.Create)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imgSrc)); encoder.Save(stream); stream.Close(); } } } else { throw new ArgumentNullException("Image source", "Method 'SaveBitmapSourceToFile' got null reference"); } }
///////图片保存//////// private void ImageSave(Canvas Canvas, string _imageFile) { double width = Canvas.ActualWidth; double height = Canvas.ActualHeight; RenderTargetBitmap bmpCopied = new RenderTargetBitmap((int)Math.Round(width), (int)Math.Round(height), 96, 96, PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(Canvas); dc.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), new System.Windows.Size(width, height))); } bmpCopied.Render(dv); using (FileStream file = new FileStream(_imageFile, FileMode.Create, FileAccess.Write)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmpCopied)); encoder.Save(file); } }
/// <summary> /// Converts to image. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">The <paramref name="bitmap"/> is <c>null</c>.</exception> public static Image ConvertToImage(this BitmapImage bitmap) { Argument.IsNotNull("bitmap", bitmap); Image image; using (MemoryStream memoryStream = new MemoryStream()) { BmpBitmapEncoder bitmapEncoder = new BmpBitmapEncoder(); bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmap)); bitmapEncoder.Save(memoryStream); image = Image.FromStream(memoryStream); } // Force garbage collection to prevent lots of memory usage GC.Collect(); return(image); }
private byte[] SignatureToBitmapBytes() { int margin = (int)this.digitalsig.Margin.Left; int width = (int)this.digitalsig.ActualWidth - margin; int height = (int)this.digitalsig.ActualHeight - margin; RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); byte[] bitmapBytes; using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); ms.Position = 0; bitmapBytes = ms.ToArray(); } return(bitmapBytes); }
private async void Save() { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Bmp (*.bmp)| *.bmp"; dialog.FileName = $"{selectedScan.offset}-{selectedScan.width}-{selectedScan.height}.bmp"; var result = dialog.ShowDialog(); if (result == true) { using (FileStream fileStream = new FileStream(dialog.FileName, FileMode.OpenOrCreate)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(this.Bitmap)); encoder.Save(fileStream); } } }
private void ConvertColors() { int width = (int)capturedImg.Source.Width; int height = (int)capturedImg.Source.Height; WriteableBitmap bitMap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null); Bitmap imageBitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(defaultImg)); encoder.Save(outStream); imageBitmap = new Bitmap(outStream); } uint[] pixels = new uint[width * height]; int red; int green; int blue; int alpha; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Color pixColor = imageBitmap.GetPixel(x, y); int i = width * y + x; red = (int)(pixColor.R * blindRed.r + pixColor.G * blindRed.g + pixColor.B * blindRed.b); green = (int)(pixColor.R * blindGreen.r + pixColor.G * blindGreen.g + pixColor.B * blindGreen.b); blue = (int)(pixColor.R * blindBlue.r + pixColor.G * blindBlue.g + pixColor.B * blindBlue.b); alpha = pixColor.A; pixels[i] = (uint)((alpha << 24) + (red << 16) + (green << 8) + blue); } } bitMap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0); capturedImg.Source = bitMap; }
public static void SaveImage(FileInfo fileInfo, BitmapSource source) { using (var fs = fileInfo.OpenWrite()) { BitmapEncoder encoder = null; switch (fileInfo.Extension) { case ".tga": //var targa = new TargaImage(source.CopyPixels()); return; case ".jpg": case ".jpeg": encoder = new JpegBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; default: throw new NotSupportedException($"File extension {fileInfo.Extension} not supported"); } encoder?.Frames.Add(BitmapFrame.Create(source)); encoder?.Save(fs); } }
private void Save() { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Ink Serialized Format (*.isf)|*.isf|" + "Bitmap files (*.bmp)|*.bmp"; bool?value = saveFileDialog.ShowDialog(); if (value.HasValue && value.Value) { try { using (FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write)) { if (saveFileDialog.FilterIndex == 1) { _drawingBoardView.InkCanvas.Strokes.Save(fileStream); fileStream.Close(); } else { int leftMargin = int.Parse(_drawingBoardView.InkCanvas.Margin.Left.ToString()); RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)_drawingBoardView.ActualWidth - leftMargin, (int)_drawingBoardView.ActualHeight - leftMargin, 0, 0, PixelFormats.Default); renderTargetBitmap.Render(_drawingBoardView.InkCanvas); BmpBitmapEncoder bmpBitmapEncoder = new BmpBitmapEncoder(); bmpBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); bmpBitmapEncoder.Save(fileStream); fileStream.Close(); } } } catch (Exception e) { MessageBox.Show(e.Message); } } }
/// <summary> /// Changes screen color from an image /// </summary> public unsafe void ChangeScreenColorFromImage(int value, Monitor monitor, BitmapImage image) { float red, green, blue; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(image)); enc.Save(outStream); using (Bitmap bmp = new Bitmap(outStream)) { if (value < 0) { value = 0; } if (value >= bmp.Width) { value = bmp.Width - 1; } Color clr = bmp.GetPixel(value, 0); red = clr.R; green = clr.G; blue = clr.B; } } ushort *gArray = stackalloc ushort[3 * 256]; for (int ik = 0; ik < 256; ik++) { gArray[ik] = (ushort)(ik * red); gArray[256 + ik] = (ushort)(ik * green); gArray[512 + ik] = (ushort)(ik * blue); } SetDeviceGammaRamp(monitor.Hdc.ToInt32(), gArray); }
public static async void UploadImageFromBitmap(String conversationID, BitmapSource image, ResultHandler handler, ErrorHandler errorHandler) { try { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add(ClientSession.HeaderToken, ChatConnection.Instance.Session.SessionID); MultipartFormDataContent form = new MultipartFormDataContent(); MemoryStream stream = new MemoryStream(); BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(image)); enc.Save(stream); form.Add(new StreamContent(stream), "file", "Clipboard.jpg"); String address = ChatConnection.Instance.WebHost; int port = ChatConnection.Instance.WebPort; String url = String.Format(MediaUploadUrl, address, port, conversationID); HttpResponseMessage response = await httpClient.PostAsync(url, form); response.EnsureSuccessStatusCode(); httpClient.Dispose(); string sd = response.Content.ReadAsStringAsync().Result; //Dic<FileName, FileID> Dictionary <String, String> result = JsonConvert.DeserializeObject <Dictionary <String, String> >(sd); handler(result); } catch (Exception e) { if (errorHandler != null) { errorHandler(e); } } }
public static byte[] ToBitmap(this FrameworkElement element) { var targetBitmap = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96d, 96d, PixelFormats.Default); targetBitmap.Render(element); // add the RenderTargetBitmap to a Bitmapencoder var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(targetBitmap)); using (var ms = new MemoryStream()) { encoder.Save(ms); return(ms.ToArray()); } }
private void SaveImage() { string fileFullName = this.DirectoryToSaveFiles + @"\" + "StrobeImage_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + ".jpeg"; int stride = m_newResultImage.BackBufferStride, height = m_newResultImage.PixelHeight; byte[] data = new byte[height * stride]; m_newResultImage.CopyPixels(data, stride, 0); using (FileStream fs = new FileStream(fileFullName, FileMode.Create)) { //fs.Write(data, 0, data.Length); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(m_newResultImage)); encoder.Save(fs); } }
public static BitmapImage BitmapSourceToImage(BitmapSource bitmapSource) { var encoder = new BmpBitmapEncoder(); using (var memoryStream = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(memoryStream); memoryStream.Position = 0; var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = memoryStream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); bitmap.Freeze(); return(bitmap); } }
//Streamに一時保存方式、BmpBitmapのエンコーダーとデコーダーを使う private BitmapSource GetClipboardBitmapEncDec() { BitmapSource source = Clipboard.GetImage(); if (source == null) { return(null); } var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); using (var stream = new System.IO.MemoryStream()) { encoder.Save(stream); stream.Seek(0, System.IO.SeekOrigin.Begin); var decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); source = decoder.Frames[0]; } return(source); }
/// <summary> /// Override the thumbnail and peek bitmap. /// By providing this bitmap manually, Thumbnail Window manager will provide the /// Desktop Window Manager (DWM) this bitmap instead of rendering one automatically. /// Use this property to update the bitmap whenever the control is updated and the user /// needs to be shown a new thumbnail on the taskbar preview (or aero peek). /// </summary> /// <param name="bitmapSource">The image to use.</param> /// <remarks> /// If the bitmap doesn't have the right dimensions, the DWM may scale it or not /// render certain areas as appropriate - it is the user's responsibility /// to render a bitmap with the proper dimensions. /// </remarks> public void SetImage(BitmapSource bitmapSource) { if (bitmapSource == null) { SetImage(IntPtr.Zero); return; } BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); using (MemoryStream memoryStream = new MemoryStream()) { encoder.Save(memoryStream); memoryStream.Position = 0; using (Bitmap bmp = new Bitmap(memoryStream)) { SetImage(bmp.GetHbitmap()); } } }
private void SavePicture() { // Görüntü dosyasını diske yazacak FileStream oluştur using (FileStream stream = new FileStream(@"D:\Temp\KinectPicture.bmp", FileMode.Create)) { // Görüntüyü farklı biçimlerde kaydedebiliyoruz. (BMP, JPEG, PNG...) // Kaydedilmek istenen görüntü türüne göre Bitmap Encoder oluştur BmpBitmapEncoder encoder = new BmpBitmapEncoder(); //JpegBitmapEncoder encoder = new JpegBitmapEncoder(); //PngBitmapEncoder encoder = new PngBitmapEncoder(); // outputImage'ı Bitmap olarak çöz ve encoder'a aktar encoder.Frames.Add(BitmapFrame.Create(outputImage)); // Görüntü dosyasını kaydet encoder.Save(stream); // FileStream'i sonlandır stream.Close(); } }
private void Button_Click(object sender, RoutedEventArgs e) { var sfd = new SaveFileDialog() { Filter = "Png files(*.png)|*.png" }; if (sfd.ShowDialog() == true) { using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(Img.bmp)); enc.Save(outStream); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream); var mp = new Bitmap(bitmap); mp.Save(sfd.FileName, ImageFormat.Png); } } }
static public System.Drawing.Bitmap ConvertBitmapSourceToBitmap(BitmapSource src) { System.Drawing.Bitmap retval = null; if (src != null) { //int width = src.PixelWidth; //int height = src.PixelHeight; //int stride = width * ((src.Format.BitsPerPixel + 7) / 8); //byte[] bits = new byte[height * stride]; using (MemoryStream strm = new MemoryStream()) { BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(strm); retval = new System.Drawing.Bitmap(strm); } } return(retval); }