public static FromStream ( Stream stream ) : Image | ||
stream | Stream | |
return | Image |
private async Task SendGifAsync(string path, List <Grid <Color> > rawFrames, int delay = 100, int?loop = null) { try { var gifStream = new MemoryStream(); using (var encoder = new GifEncoder(gifStream)) { List <Bitmap> frames = rawFrames.Select(f => ImageHelper.CreateRgbBitmap(f.Values)).ToList(); encoder.FrameLength = TimeSpan.FromMilliseconds(delay); foreach (Bitmap frame in frames) { using (frame) encoder.EncodeFrame(frame); } } gifStream.Position = 0; Image gifResult = Image.FromStream(gifStream); gifResult.Save(path, ImageFormat.Gif); await gifStream.DisposeAsync(); await Context.Channel.SendFileAsync(path); } catch (Exception ex) { await Context.Channel.CatchAsync(ex); } finally { //File.Delete(path); } }
public async Task DrawAnimAsync(int millisecondDelay, params string[] strings) { string gifPath = $"../tmp/{Context.User.Id}_anim.gif"; FontFace font = JsonHandler.Load <FontFace>(@"../assets/fonts/orikos.json"); MemoryStream gifStream = new MemoryStream(); using (GifEncoder encoder = new GifEncoder(gifStream)) { encoder.FrameLength = TimeSpan.FromMilliseconds(millisecondDelay); foreach (Stream frame in GetTextFrames(strings)) { using (frame) encoder.EncodeFrame(Image.FromStream(frame)); } } gifStream.Position = 0; Image gifResult = Image.FromStream(gifStream); gifResult.Save(gifPath, ImageFormat.Gif); gifStream.Dispose(); await Context.Channel.SendFileAsync(gifPath); //await Context.Channel.SendFileAsync(gifStream, "gif_test.gif"); }
public async Task RunLifeAsync(int width, int height, int duration, int delay = 100) { string path = $"../tmp/{Context.User.Id}_cgol.gif"; GammaPalette colors = GammaPalette.Glass; Grid <ConwayCell> pattern = ConwayRenderer.GetRandomPattern(width, height); ConwayRenderer simulator = new ConwayRenderer(colors[Gamma.Max], colors[Gamma.Min], null, pattern); List <Grid <Color> > rawFrames = simulator.Run(duration); MemoryStream gifStream = new MemoryStream(); using (GifEncoder encoder = new GifEncoder(gifStream)) { List <Bitmap> frames = rawFrames.Select(f => ImageHelper.CreateRgbBitmap(f.Values)).ToList(); encoder.FrameLength = TimeSpan.FromMilliseconds(delay); foreach (Bitmap frame in frames) { using (frame) encoder.EncodeFrame(frame); } } gifStream.Position = 0; Image gifResult = Image.FromStream(gifStream); gifResult.Save(path, ImageFormat.Gif); await gifStream.DisposeAsync(); await Context.Channel.SendFileAsync(path); }
private void LoadLicniPodaciInTxt() { txtRole.Text = Auth.Role.ToTitleString(); txtIme.Text = LicniPodaci.Ime; txtPrezime.Text = LicniPodaci.Prezime; lblFirstLastName.Text = $"{LicniPodaci.Ime} {LicniPodaci.Prezime}"; txtJmbg.Text = LicniPodaci.JMBG; txtEmail.Text = LicniPodaci.EmailAddress; txtAdresa.Text = LicniPodaci.Adresa; txtDateCreated.Text = Auth.KorisnickiNalog.DateCreated; txtBrojTelefona.Text = LicniPodaci.BrojTelefona; if (LicniPodaci.ProfilePicture.Length > 0) { var imageFromStream = Image.FromStream(new MemoryStream(LicniPodaci.ProfilePicture)); picProfilePicture.Image = imageFromStream; } cmbPolovi.SelectedIndex = char.ToLower(LicniPodaci.Pol) == 'm' ? 0 : 1; cmbDrzave.SelectedValue = LicniPodaci.Grad?.DrzavaId ?? 0; if (LicniPodaci.Grad != null) { cmbGradovi.SelectedValue = LicniPodaci.Grad.Id; } }
public static Image LoadImageToBitmap(string fullname) { string extension = Path.GetExtension(fullname).ToUpper(); if (!Filter.ExtensionsList.Contains(extension)) { return(null); } Image image = null; string[] simpleFormats = new string[] { "*.BMP", ".DIB", ".RLE", ".GIF", ".JPG", ".PNG", ".JPEG" }; if (simpleFormats.Contains(extension)) { using (MemoryStream memory = new MemoryStream()) using (FileStream fs = new FileStream(fullname, FileMode.Open, FileAccess.ReadWrite)) image = Image.FromStream(fs); } else { using (var img = LoadImage(new FileInfo(fullname))) image = ConvertToBitmap(img); } return(image); }
internal RtfImage(System.IO.MemoryStream imageStream, ReadingDirection direction) { ReadingDirection = direction; _alignment = Align.Left; _margins = new Margins(); _keepAspectRatio = true; _blockHead = @"{\pard"; _blockTail = @"}"; _startNewPage = false; _startNewPara = false; _imgByte = imageStream.ToArray(); Image image = Image.FromStream(imageStream); _width = (image.Width / image.HorizontalResolution) * 72; _height = (image.Height / image.VerticalResolution) * 72; if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) { _imgType = ImageFileType.Png; } else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) { _imgType = ImageFileType.Jpg; } else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) { _imgType = ImageFileType.Gif; } else { throw new Exception("Image format is not supported: " + image.RawFormat.ToString()); } }
private void btnBrowser_Click(object sender, EventArgs e) { this.pteLogo.Location = new System.Drawing.Point(90, 98); this.pteLogo.Name = "pictureBox1"; this.pteLogo.Size = new System.Drawing.Size(200, 95); this.pteLogo.TabIndex = 1; this.pteLogo.TabStop = false; OpenFileDialog logo = new OpenFileDialog(); logo.Filter = "Images (*.jpg)|*.jpg"; if (logo.ShowDialog() == DialogResult.OK) { txtLogo.Text = logo.FileName; } //---------upload anh logo len server 17/06/2013 Upload(txtLogo.Text, "192.168.8.15", "pos", "pos@TA1174&&?"); string path = String.Format("http://logo.trananh.com.vn/{0}.jpg", txtNhaCC.Text); System.Net.WebRequest req = System.Net.WebRequest.Create(path); System.Net.WebResponse response = req.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); if (path != null) { //Image im = new Bitmap(path, true); Image im = Image.FromStream(stream); pteLogo.Image = im; //Crop(im, 192, 83, AnchorPosition.Center); } }
/// <summary> /// Draw a bitmap on the Render Target (Game Launcher Window). /// </summary> /// <param name="target">Destination render target which is ready to be drawn.</param> /// <param name="bitmapData">Bitmap data.</param> /// <param name="windowSize">Destination window size.</param> /// <param name="rect">Which rectangle range on the render target(window) should be drawn by the bitmap?</param> /// <param name="opacity">What opacity we should use to draw the bitmap? (Range: [0,1])</param> /// <param name="isFlushInstantly">Should we flush render target instantly after drawing the bitmap?</param> public static void DrawBitmap(D2D.RenderTarget target, byte[] bitmapData, Size2F windowSize, RawRectangleF rect, float opacity = 1.0f, bool isFlushInstantly = true) { var stream = new MemoryStream(bitmapData); stream.Seek(0, SeekOrigin.Begin); var bitmapWrapper = (Bitmap)Image2.FromStream(stream); if (bitmapWrapper.Width > windowSize.Width) { bitmapWrapper = bitmapWrapper.ScaleBitmap((double)windowSize.Width / bitmapWrapper.Width); } else if (bitmapWrapper.Height > windowSize.Height) { bitmapWrapper = bitmapWrapper.ScaleBitmap((double)windowSize.Height / bitmapWrapper.Height); } var bitmap = target.LoadD2DBitmapFromBitmap(bitmapWrapper); if (bitmap != null) { target.DrawBitmap(bitmap, opacity, D2D.BitmapInterpolationMode.Linear, rect); if (isFlushInstantly) { target.Flush(); } } }
private byte[] ProcessImage(byte[] imageBytes, IList <Rectangle> areasToBeCleaned) { if (areasToBeCleaned.Count == 0) { return(imageBytes); } using (Stream imageStream = new MemoryStream(imageBytes)) { SharpImage image = SharpImage.FromStream(imageStream); CleanImage(image, areasToBeCleaned); using (MemoryStream outStream = new MemoryStream()) { if (Equals(image.RawFormat, ImageFormat.Tiff)) { EncoderParameters encParams = new EncoderParameters(1); encParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); image.Save(outStream, GetEncoderInfo(image.RawFormat), encParams); } else if (Equals(image.RawFormat, ImageFormat.Jpeg)) { EncoderParameters encParams = new EncoderParameters(1); encParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L); image.Save(outStream, GetEncoderInfo(image.RawFormat), encParams); } else { image.Save(outStream, image.RawFormat); } return(outStream.ToArray()); } } }
//edit student in print form (click cell in dgv) private void StudentDgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { FormEditRemove edit = new FormEditRemove(); edit.ID_txt.Text = info_dgv.CurrentRow.Cells[0].Value.ToString(); edit.fName_txt.Text = info_dgv.CurrentRow.Cells[1].Value.ToString(); edit.lName_txt.Text = info_dgv.CurrentRow.Cells[2].Value.ToString(); edit.dateTimePicker1.Value = (DateTime)info_dgv.CurrentRow.Cells[3].Value; if ((info_dgv.CurrentRow.Cells[4].Value.ToString() == "Female ")) { edit.fMale_rbtn.Checked = true; } else { edit.Male_rbtn.Checked = true; } edit.phone_txt.Text = info_dgv.CurrentRow.Cells[5].Value.ToString(); edit.address_txt.Text = info_dgv.CurrentRow.Cells[6].Value.ToString(); byte[] pic; pic = (byte[])info_dgv.CurrentRow.Cells[7].Value; MemoryStream picture = new MemoryStream(pic); edit.picture_ptb.Image = Image.FromStream(picture); edit.Show(); }
private bool ShouldPdfOptimized(Document pdfDocument, string path) { var imagesTooBigCount = 0; foreach (Page pdfPage in pdfDocument.Pages) { // Only do the check if there is exactly one image on the page (scans) if (pdfPage?.Resources.Images.Count == 1) { XImage image = pdfPage.Resources.Images[1]; var stream = new MemoryStream(); image.Save(stream); var bitmap = Image.FromStream(stream); if (IsImageTooBig(bitmap, stream.Length, path)) { imagesTooBigCount++; // Check if we already skipped the threshold if (imagesTooBigCount * 100.0 / pdfDocument.Pages.Count > settings.AllowTooBigPercentage) { return(true); } } } } // if we come here, we don't enough images that are too big return(false); }
private void dataGridViewCozumEkle_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { tableLayoutPanel4.Controls.Clear(); string id = dataGridViewCozumEkle.Rows[dataGridViewCozumEkle.CurrentRow.Index].Cells["Hata_Id"].Value.ToString(); DataGridViewSelectGlobalHata = contextDb.Hata.FirstOrDefault(h => h.hataID.ToString() == id); textBoxCozumAciklama.Text = DataGridViewSelectGlobalHata.hataCozum; textBoxCozumTanım.Text = DataGridViewSelectGlobalHata.hataAd; textBoxHataAciklama.Text = DataGridViewSelectGlobalHata.hataAciklama; if (DataGridViewSelectGlobalHata != null) { var HataResimler = contextDb.HataResimler.Where(r => r.hataID == DataGridViewSelectGlobalHata.hataID).ToList(); if (HataResimler != null) { foreach (var item in HataResimler) { byte[] a = item.Resimler.resimData; MemoryStream ms = new MemoryStream(a); Image img = Image.FromStream(ms); PictureBox picture = new PictureBox(); picture.MouseClick += Picture_MouseClick; picture.SizeMode = PictureBoxSizeMode.StretchImage; picture.Image = img; tableLayoutPanel4.Controls.Add(picture); } } } }
protected void ImageResize(string path, string dest, int width, int height) { FileStream fs = new FileStream(path, FileMode.Open); Image img = Image.FromStream(fs); fs.Close(); fs.Dispose(); float ratio = (float)img.Width / (float)img.Height; if ((img.Width <= width && img.Height <= height) || (width == 0 && height == 0)) { return; } int newWidth = width; int newHeight = Convert.ToInt16(Math.Floor((float)newWidth / ratio)); if ((height > 0 && newHeight > height) || (width == 0)) { newHeight = height; newWidth = Convert.ToInt16(Math.Floor((float)newHeight * ratio)); } Bitmap newImg = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage((Image)newImg); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(img, 0, 0, newWidth, newHeight); img.Dispose(); g.Dispose(); if (dest != "") { newImg.Save(dest, GetImageFormat(dest)); } newImg.Dispose(); }
static Texture2D LoadTexture(FoamExtension Ext) { using (MemoryStream MS = new MemoryStream(Ext.Data)) { MS.Seek(0, SeekOrigin.Begin); using (Bitmap Bmp = new Bitmap(NetImage.FromStream(MS))) { BitmapData Data = Bmp.LockBits(new System.Drawing.Rectangle(0, 0, Bmp.Width, Bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); uint * OrigColors = (uint *)Data.Scan0; int Len = Bmp.Width * Bmp.Height; uint *Colors = (uint *)Marshal.AllocHGlobal(Len * sizeof(uint)); for (int i = 0; i < Len; i++) { uint Orig = OrigColors[i]; byte R = (byte)((Orig >> 16) & 255); byte G = (byte)((Orig >> 8) & 255); byte B = (byte)((Orig >> 0) & 255); byte A = (byte)((Orig >> 24) & 255); Colors[i] = (uint)((R << 0) | (G << 8) | (B << 16) | (A << 24)); } Image Img = Raylib.LoadImagePro(new IntPtr(Colors), Bmp.Width, Bmp.Height, (int)RaylibSharp.PixelFormat.UNCOMPRESSED_R8G8B8A8); Marshal.FreeHGlobal(new IntPtr(Colors)); Bmp.UnlockBits(Data); return(LoadTexture(Img)); } } }
public void Configure(DriverDetails driverDetails) { client = new OpenRGBClient(name: "RGB Sync Studio", autoconnect: true, timeout: 1000); var deviceCount = client.GetControllerCount(); var devices = client.GetAllControllerData(); for (int devId = 0; devId < devices.Length; devId++) { ORGBControlDevice slsDevice = new ORGBControlDevice(); slsDevice.id = devId; slsDevice.Driver = this; slsDevice.Name = devices[devId].Name; slsDevice.DeviceType = DeviceTypeConverter.GetType(devices[devId].Type); slsDevice.Has2DSupport = false; slsDevice.ProductImage = (Bitmap)Image.FromStream(orgbImage); List <ControlDevice.LedUnit> deviceLeds = new List <ControlDevice.LedUnit>(); int i = 0; foreach (Led orgbLed in devices[devId].Leds) { ControlDevice.LedUnit slsLed = new ControlDevice.LedUnit(); slsLed.LEDName = orgbLed.Name; deviceLeds.Add(slsLed); } slsDevice.LEDs = deviceLeds.ToArray(); DeviceAdded?.Invoke(slsDevice, new Events.DeviceChangeEventArgs(slsDevice)); } }
private Image LoadImage(string imageExpression) { try { using (IDataValue imageData = FrontendSession.Pipe.RequestDocument(imageExpression)) { var streamCopy = new MemoryStream(); Stream stream = imageData.OpenStream(); try { StreamUtility.CopyStream(stream, streamCopy); } finally { stream.Close(); } return(Image.FromStream(streamCopy)); } } catch (Exception exception) { Dataphoria.Warnings.AppendError(this, exception, true); // Don't rethrow } return(null); }
/// <summary> /// 字节流转换成图片 /// </summary> /// <param name="byt">要转换的字节流</param> /// <returns>转换得到的Image对象</returns> public static Image BytToImg(byte[] byt) { MemoryStream ms = new MemoryStream(byt); Image img = Image.FromStream(ms); return(img); }
public static string ResizeBase64ImageString(string Base64String, int desiredWidth, int desiredHeight) { Base64String = Base64String.Replace("data:image/png;base64,", ""); // Convert Base64 String to byte[] byte[] imageBytes = Convert.FromBase64String(Base64String); using (MemoryStream ms = new MemoryStream(imageBytes)) { // Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length); DImage image = DImage.FromStream(ms, true); var imag = ScaleImage(image, desiredWidth, desiredHeight); using (MemoryStream ms1 = new MemoryStream()) { //First Convert Image to byte[] imag.Save(ms1, image.RawFormat); byte[] imageBytes1 = ms1.ToArray(); //Then Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes1); //return "data:image/png;base64," + base64String; return(base64String); } } }
/// <summary> /// Uploads a posted image to the candidate photo repository for the current candidate. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An <see cref="EventArgs"/> object that contains the event data.</param> protected void UploadPhoto(object sender, EventArgs e) { if (Page.IsValid && this.IsPostBack) { // upload image try { if (_photoUpload.HasFile) { try { using (Image i = Image.FromStream(_photoUpload.FileContent, true, true)) { if (_photoUpload.FileContent.Length <= MaxPhotoFileSizeMB * BytesPerMegabyte) { string photoPath = ProfilePhotoHandler.GetPhotoFilePath(CPProfile.Cid); if (File.Exists(photoPath) && !string.IsNullOrEmpty(CPProfile.Cid)) { File.Delete(photoPath); } if ((i.Height > MaxPhotoHeight) || (i.Width > MaxPhotoWidth)) { using (Image t = MakeThumbnailFrom(i)) { t.Save(photoPath); } } else { i.Save(photoPath); } i.Dispose(); ShowGreeting(); } else { // when file is too big SetError(string.Format("The file provided exceeds the maximum acceptable image size of {0} MB. Please try uploading a smaller file.", MaxPhotoFileSizeMB)); } } } catch (ArgumentException) { // when file is valid but not an image SetError("The file provided is not a supported image. Please try uploading a BMP, GIF, JPG, TIF, or PNG file."); } } else { // when no file was supplied SetError("Please first browse to an image for uploading."); } } catch (ArgumentException) { // when an invalid path was supplied SetError("The file specified could not be found. Please try browsing to the file again."); } } }
/// 图片裁剪,生成新图,保存在同一目录下,名字加_new,格式1.png 新图1_new.png /// </summary> /// <param name="picPath">要修改图片完整路径</param> /// <param name="x">修改起点x坐标</param> /// <param name="y">修改起点y坐标</param> /// <param name="width">新图宽度</param> /// <param name="height">新图高度</param> private static string cutPicture(String picPath, int x, int y, int width, int height, int index) { //图片路径 String oldPath = picPath; //新图片路径 String newPath = Path.GetExtension(oldPath); //计算新的文件名,在旧文件名后加_new newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_" + index + newPath; //定义截取矩形 Rectangle cropArea = new Rectangle(x, y, width, height); //要截取的区域大小 //加载图片 Image img = Image.FromStream(new MemoryStream(File.ReadAllBytes(oldPath))); //判断超出的位置否 if ((img.Width < x + width) || img.Height < y + height) { //MessageBox.Show("裁剪尺寸超出原有尺寸!"); img.Dispose(); return(""); } //定义Bitmap对象 Bitmap bmpImage = new Bitmap(img); //进行裁剪 Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); //保存成新文件 bmpCrop.Save(newPath, ImageFormat.Jpeg); //释放对象 img.Dispose(); bmpCrop.Dispose(); return(newPath); }
private void bteSanPham_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { frmLookUp_SanPham frmLookUpSanPham = new frmLookUp_SanPham(false, String.Format("%{0}%", bteSanPham.Text)); if (frmLookUpSanPham.ShowDialog() == DialogResult.OK) { bteSanPham.Tag = frmLookUpSanPham.SelectedItem; bteSanPham.Text = frmLookUpSanPham.SelectedItem.TenSanPham; DMCauHinhSanPhamInfo obj = DMCauHinhSanPhamDataProvider.Instance.GetNhaCCByIdSanPham(((DMSanPhamInfo)bteSanPham.Tag).IdSanPham); txtNhaCC.Text = obj.Hang; try { string path = String.Format("http://logo.trananh.com.vn/{0}.jpg", txtNhaCC.Text); System.Net.WebRequest req = System.Net.WebRequest.Create(path); System.Net.WebResponse response = req.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); if (path != null) { //Image im = new Bitmap(path, true); Image im = Image.FromStream(stream); pteLogo.Size = new Size(192, 83); pteLogo.Image = Crop(im, 192, 83, AnchorPosition.Center); } } catch (Exception) { clsUtils.MsgCanhBao("Sản phẩm chưa có Logo!"); } } } }
// Resize Image public static string ResizeImage(byte[] byteArrayIn, int width, int height) { using (var ms = new MemoryStream(byteArrayIn)) { Image image = Image.FromStream(ms); var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } Bitmap bImage = destImage; System.IO.MemoryStream ms1 = new MemoryStream(); bImage.Save(ms1, ImageFormat.Jpeg); byte[] byteImage = ms1.ToArray(); var SigBase64 = Convert.ToBase64String(byteImage); return(SigBase64); } }
public override Image ApplyTransformation(Image image) { // Use original image dimensions if user didn't specify any. if (Width == 0) { Debug.Assert(Height == 0, "If one dimension is zero the other one must be too."); Width = WatermarkImage.Width; Height = WatermarkImage.Height; } if (((Padding * 2) + Width >= image.Width) || ((Padding * 2) + Height >= image.Height)) { // If watermark image + padding is too big we don't make any changes. return(image); } WatermarkImage.Resize(Width, Height, preserveAspectRatio: false, preventEnlarge: false); float alphaScaling = ((float)Opacity) / 100; byte[] watermarkBuffer = WatermarkImage.GetBytes(); Rectangle rect = GetRectangleInsideImage(image, Width, Height); using (Graphics targetGraphics = Graphics.FromImage(image)) { using (MemoryStream memStream = new MemoryStream(watermarkBuffer)) { using (Image watermarkImage = Image.FromStream(memStream)) { AddWatermark(targetGraphics, watermarkImage, rect, alphaScaling); } } } return(image); }
/// <summary> /// Constructs a System.Drawing.Image instance from the content which validates the contents of the image. /// </summary> /// <exception cref="System.ArgumentException">When an Image construction fails.</exception> private static ImageFormat ValidateImageContent(byte[] content, string paramName) { try { using (MemoryStream stream = new MemoryStream(content)) { using (Image image = Image.FromStream(stream, useEmbeddedColorManagement: false)) { var rawFormat = image.RawFormat; ImageFormat actualFormat; // RawFormat returns a ImageFormat instance with the same Guid as the predefined types // This instance is not very useful when it comes to printing human readable strings and file extensions. // Therefore, lookup the predefined instance if (!_imageFormatLookup.TryGetValue(rawFormat.Guid, out actualFormat)) { actualFormat = rawFormat; } return(actualFormat); } } } catch (ArgumentException exception) { throw new ArgumentException(HelpersResources.WebImage_InvalidImageContents, paramName, exception); } }
public static Image Crop(Image Image, int newWidth, int newHeight, int startX = 0, int startY = 0) { if (Image.Height < newHeight) newHeight = Image.Height; if (Image.Width < newWidth) newWidth = Image.Width; using (var bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb)) { bmp.SetResolution(72, 72); using (var g = Graphics.FromImage(bmp)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(Image, new Rectangle(0, 0, newWidth, newHeight), startX, startY, newWidth, newHeight, GraphicsUnit.Pixel); var ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Png); Image.Dispose(); var outimage = Image.FromStream(ms); return outimage; } } }
/// <summary> /// Compare Capture.Rectangle(element.Bounds) to the expected image. /// </summary> /// <param name="fileName">Can be a full file name relative filename or the name of a resource.</param> /// <param name="element">The UIElement.</param> /// <param name="onFail">Useful for saving the actual image on error for example.</param> public static void AreEqual(string fileName, UIElement element, Action <Exception, Bitmap> onFail) { if (TryGetStream(fileName, Assembly.GetCallingAssembly(), out var stream)) { using (stream) { using (var expected = (Bitmap)Image.FromStream(stream)) { using (var actual = element.ToBitmap(expected.Size(), expected.PixelFormat())) { try { AreEqual(expected, actual); } catch (Exception e) { onFail(e, actual); throw; } } } } } else { var exception = AssertException.Create($"Did not find a file nor resource named {fileName}"); using (var actual = element.ToBitmap(element.RenderSize, GetPixelFormat(fileName))) { onFail(exception, actual); } throw exception; } }
public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return(returnImage); }
/// <summary> /// Compare Capture.Rectangle(element.Bounds) to the expected image. /// </summary> /// <param name="fileName">Can be a full file name relative filename or the name of a resource.</param> /// <param name="element">The automation element.</param> /// <param name="onFail">Useful for saving the actual image on error for example.</param> public static void AreEqual(string fileName, AutomationElement element, Action <Exception, Bitmap> onFail) { WaitForStartAnimation(element); if (TryGetStream(fileName, Assembly.GetCallingAssembly(), out var stream)) { using (stream) { using (var expected = (Bitmap)Image.FromStream(stream)) { using (var actual = Capture.Rectangle(element.Bounds)) { try { AreEqual(expected, actual); } catch (Exception e) { onFail(e, actual); throw; } } } } } else { var exception = AssertException.Create($"Did not find a file nor resource named {fileName}"); using (var actual = Capture.Rectangle(element.Bounds)) { onFail(exception, actual); } throw exception; } }
protected override void InitializeStatusBar() { base.InitializeStatusBar(); this._executionTimeStatus = new ToolStripStatusLabel { Name = "FExecutionTimeStatus", Alignment = ToolStripItemAlignment.Right, MergeIndex = 150, BorderSides = ToolStripStatusLabelBorderSides.All, Text = "0:00:00", DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text }; const string cResourceName = "Alphora.Dataphor.Dataphoria.Images.Rider.gif"; Stream manifestResourceStream = GetType().Assembly.GetManifestResourceStream(cResourceName); Error.AssertFail(manifestResourceStream != null, "Resource must exist: " + cResourceName); _workingAnimation = new PictureBox { Image = Image.FromStream(manifestResourceStream), SizeMode = PictureBoxSizeMode.AutoSize }; _workingStatus = new ToolStripControlHost(_workingAnimation, "FWorkingStatus") { Size = _workingAnimation.Size, Visible = false, Alignment = ToolStripItemAlignment.Right, }; FStatusStrip.Items.Add(_executionTimeStatus); FStatusStrip.Items.Add(_workingStatus); }
private byte[] ProcessImages(List <byte[]> images) { using (MemoryStream backgroundStream = new MemoryStream(Pattern.Data)) { Image backgroundImage = Image.FromStream(backgroundStream); using (Bitmap backgroundBitmap = new Bitmap(backgroundImage.Width, backgroundImage.Height)) { using (Graphics canvas = Graphics.FromImage(backgroundBitmap)) { canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; canvas.DrawImage(backgroundImage, new Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height), new Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height), GraphicsUnit.Pixel); int destWidth = backgroundBitmap.Width / 5; int destHeight = backgroundBitmap.Height / 5; int stepX = backgroundBitmap.Width / 6; int stepY = backgroundBitmap.Height / 6; FillCanvas(canvas, images[0], new Point(stepX, stepY), destWidth, destHeight, 0, 0); FillCanvas(canvas, images[1], new Point(2 * stepX, stepY), destWidth, destHeight, destWidth, 0); FillCanvas(canvas, images[2], new Point(stepX, 2 * stepY), destWidth, destHeight, 0, destHeight); canvas.Save(); } return(backgroundBitmap.ToBytes()); } } }
private static void DrawImage(Ressource image, Graphics graphics, IMyCollectionsData entity, PrintDocument printDocument) { MemoryStream objImageMemory = new MemoryStream(image.Value, 0, image.Value.Length); objImageMemory.Write(image.Value, 0, image.Value.Length); Image imgCover = Image.FromStream(objImageMemory, true); if ((entity.ObjectType == EntityType.Music || entity.ObjectType == EntityType.Games || entity.ObjectType == EntityType.Nds) && image.IsDefault == true) { graphics.DrawImage(imgCover, new Rectangle(100, 100, 473, 473)); } else if (image.IsDefault == true) { graphics.DrawImage(imgCover, new Rectangle(100, 100, 524, 721)); } else if (imgCover.Width > printDocument.DefaultPageSettings.PrintableArea.Width || imgCover.Height > printDocument.DefaultPageSettings.PrintableArea.Height) { graphics.DrawImage(imgCover, new Rectangle(100, 100, (int)printDocument.DefaultPageSettings.PrintableArea.Width - 200, (int)printDocument.DefaultPageSettings.PrintableArea.Height - 200)); } else { graphics.DrawImage(imgCover, new Rectangle(100, 100, imgCover.Width - 200, imgCover.Height - 200)); } imgCover.Dispose(); objImageMemory.Dispose(); }
//The crop image sub public static Image CropImage(Image Image, int Height, int Width, int StartAtX, int StartAtY) { Image outimage; MemoryStream mm = null; try { //check the image height against our desired image height if (Image.Height < Height) { Height = Image.Height; } if (Image.Width < Width) { Width = Image.Width; } //create a bitmap window for cropping Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(72, 72); //create a new graphics object from our image and set properties Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.SmoothingMode = SmoothingMode.AntiAlias; grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality; //now do the crop grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel); // Save out to memory and get an image from it to send back out the method. mm = new MemoryStream(); bmPhoto.Save(mm, ImageFormat.Jpeg); Image.Dispose(); bmPhoto.Dispose(); grPhoto.Dispose(); outimage = Image.FromStream(mm); return outimage; } catch (Exception ex) { throw new Exception("Error cropping image, the error was: " + ex.Message); } }