public Terrain(Device device, String texture, int pitch, Renderer renderer) { HeightMap = new System.Drawing.Bitmap(@"Data/Textures/"+texture); WaterShader = new WaterShader(device); TerrainShader = new TerrainShader(device); _width = HeightMap.Width-1; _height = HeightMap.Height-1; _pitch = pitch; _terrainTextures = new ShaderResourceView[4]; _terrainTextures[0] = new Texture(device, "Sand.png").TextureResource; _terrainTextures[1] = new Texture(device, "Grass.png").TextureResource; _terrainTextures[2] = new Texture(device, "Ground.png").TextureResource; _terrainTextures[3] = new Texture(device, "Rock.png").TextureResource; _reflectionClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 0.0f); _refractionClippingPlane = new Vector4(0.0f, -1.0f, 0.0f, 0.0f); _noClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 10000); _reflectionTexture = new RenderTexture(device, renderer.ScreenSize); _refractionTexture = new RenderTexture(device, renderer.ScreenSize); _renderer = renderer; _bitmap = new Bitmap(device,_refractionTexture.ShaderResourceView,renderer.ScreenSize, new Vector2I(100, 100), 0); _bitmap.Position = new Vector2I(renderer.ScreenSize.X - 100, 0); _bitmap2 = new Bitmap(device, _reflectionTexture.ShaderResourceView, renderer.ScreenSize, new Vector2I(100, 100), 0); _bitmap2.Position = new Vector2I(renderer.ScreenSize.X - 100, 120); _bumpMap = _renderer.TextureManager.Create("OceanWater.png"); _skydome = new ObjModel(device, "skydome.obj", renderer.TextureManager.Create("Sky.png")); BuildBuffers(device); WaveTranslation = new Vector2(0,0); }
private void TakeScreenshot(TestContext testContext) { var filename = Path.GetFullPath(testContext.FullyQualifiedTestClassName + ".jpg"); try { var screenLeft = SystemInformation.VirtualScreen.Left; var screenTop = SystemInformation.VirtualScreen.Top; var screenWidth = SystemInformation.VirtualScreen.Width; var screenHeight = SystemInformation.VirtualScreen.Height; // Create a bitmap of the appropriate size to receive the screenshot. using (var bmp = new Bitmap(screenWidth, screenHeight)) { // Draw the screenshot into our bitmap. using (var g = Graphics.FromImage(bmp)) { g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size); } bmp.Save(filename, ImageFormat.Jpeg); } testContext.AddResultFile(filename); } catch (Exception ex) { Logger.WriteLine("An exception occured while trying to take screenshot:"); Logger.WriteLine(ex); } }
public Bitmap ToBitmap(Bitmap.Config config) { System.Drawing.Size size = Size; if (config == Bitmap.Config.Argb8888) { Bitmap result = Bitmap.CreateBitmap(size.Width, size.Height, Bitmap.Config.Argb8888); using (BitmapArgb8888Image bi = new BitmapArgb8888Image(result)) using (Image<Rgba, Byte> tmp = ToImage<Rgba, Byte>()) { tmp.Copy(bi, null); } return result; } else if (config == Bitmap.Config.Rgb565) { Bitmap result = Bitmap.CreateBitmap(size.Width, size.Height, Bitmap.Config.Rgb565); using (BitmapRgb565Image bi = new BitmapRgb565Image(result)) using (Image<Bgr, Byte> tmp = ToImage<Bgr, Byte>()) bi.ConvertFrom(tmp); return result; } else { throw new NotImplementedException("Only Bitmap config of Argb888 or Rgb565 is supported."); } }
public static void FindBlackRegionSize(Bitmap source, ref int leftH, ref int leftW, ref int rightH, ref int rightW) { int i = 0, j = 0; int w = source.Width; int h = source.Height; BitmapData sourceData = source.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); leftH = leftW = int.MaxValue; rightH = rightW = int.MinValue; unsafe { byte* sourcePtr = (byte*)sourceData.Scan0; for (i = 0; i < h; ++i) { for (j = 0; j < w; ++j) { if (sourcePtr[i * sourceData.Stride + j * 3] == 0) { if (i < leftH) { leftH = i; } if (i > rightH) { rightH = i; } if (j < leftW) { leftW = j; } if (j > rightW) { rightW = j; } } } } source.UnlockBits(sourceData); } GC.Collect(0); }
private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size) { //int sourceWidth = imgToResize.Width; //int sourceHeight = imgToResize.Height; //float nPercent = 0; //float nPercentW = 0; //float nPercentH = 0; //nPercentW = ((float)size.Width / (float)sourceWidth); //nPercentH = ((float)size.Height / (float)sourceHeight); //if (nPercentH < nPercentW) // nPercent = nPercentH; //else // nPercent = nPercentW; //int destWidth = (int)(sourceWidth * nPercent); //int destHeight = (int)(sourceHeight * nPercent); int destWidth = size.Width; int destHeight = size.Height; Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((System.Drawing.Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (System.Drawing.Image)b; }
public static void Main(string[] args) { Graphics.DrawImageAbort imageCallback; Bitmap outbmp = new Bitmap (300, 300); Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Graphics dc = Graphics.FromImage (outbmp); ImageAttributes imageAttr = new ImageAttributes(); /* Simple image drawing */ dc.DrawImage(bmp, 0,0); /* Drawing using points */ PointF ulCorner = new PointF(150.0F, 0.0F); PointF urCorner = new PointF(350.0F, 0.0F); PointF llCorner = new PointF(200.0F, 150.0F); RectangleF srcRect = new Rectangle (0,0,100,100); PointF[] destPara = {ulCorner, urCorner, llCorner}; imageCallback = new Graphics.DrawImageAbort(DrawImageCallback); dc.DrawImage (bmp, destPara, srcRect, GraphicsUnit.Pixel, imageAttr, imageCallback); /* Using rectangles */ RectangleF destRect = new Rectangle (10,200,100,100); RectangleF srcRect2 = new Rectangle (50,50,100,100); dc.DrawImage (bmp, destRect, srcRect2, GraphicsUnit.Pixel); /* Simple image drawing with with scaling*/ dc.DrawImage(bmp, 200,200, 75, 75); outbmp.Save("drawimage.bmp", ImageFormat.Bmp); }
protected void Page_Load(object sender, EventArgs e) { if (CheckAuthentication()) { string s = HttpContext.Current.Request.Form["fileUpload"] as string; if (!string.IsNullOrEmpty(s)) { string strSaveLocation = string.Empty; try { Bitmap img = new Bitmap(HttpContext.Current.Request.Files[0].InputStream, false); } catch (Exception) { strSaveLocation = "LargeImagePixel"; return; } string strFileName = Path.GetFileName(HttpContext.Current.Request.Files[0].FileName); string strExtension = Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower(); string strBaseLocation = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\"); //HttpContext.Current.Server.MapPath("~/bin/"); if (!Directory.Exists(strBaseLocation)) { Directory.CreateDirectory(strBaseLocation); } strSaveLocation = strBaseLocation + strFileName; HttpContext.Current.Request.Files[0].SaveAs(strSaveLocation); //strSaveLocation = strSaveLocation.Replace(HttpContext.Current.Server.MapPath("~/"), ""); //strSaveLocation = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\"); //strSaveLocation.Replace("\\", "/"); HttpContext.Current.Response.ContentType = "text/plain"; HttpContext.Current.Response.Write("({ 'Message': '" + strSaveLocation + "' })"); HttpContext.Current.Response.End(); } } }
private BitmapBrush CreateDirectBrush( ImageBrush brush, SharpDX.Direct2D1.RenderTarget target, Bitmap image, Rect sourceRect, Rect destinationRect) { var tileMode = brush.TileMode; var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size); var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale); var transform = Matrix.CreateTranslation(-sourceRect.Position) * Matrix.CreateScale(scale) * Matrix.CreateTranslation(translate); var opts = new BrushProperties { Transform = transform.ToDirect2D(), Opacity = (float)brush.Opacity, }; var bitmapOpts = new BitmapBrushProperties { ExtendModeX = GetExtendModeX(tileMode), ExtendModeY = GetExtendModeY(tileMode), }; return new BitmapBrush(target, image, bitmapOpts, opts); }
protected internal override void RenderRectangle(Bitmap bmp, Pen pen, int x, int y, int width, int height) { Color outlineColor = (pen != null) ? pen.Color : (Color)0x0; ushort outlineThickness = (pen != null) ? pen.Thickness : (ushort)0; int x1, y1; int x2, y2; switch (MappingMode) { case BrushMappingMode.RelativeToBoundingBox: x1 = x + (int)((long)(width - 1) * StartX / RelativeBoundingBoxSize); y1 = y + (int)((long)(height - 1) * StartY / RelativeBoundingBoxSize); x2 = x + (int)((long)(width - 1) * EndX / RelativeBoundingBoxSize); y2 = y + (int)((long)(height - 1) * EndY / RelativeBoundingBoxSize); break; default: //case BrushMappingMode.Absolute: x1 = StartX; y1 = StartY; x2 = EndX; y2 = EndY; break; } bmp.DrawRectangle(outlineColor, outlineThickness, x, y, width, height, 0, 0, StartColor, x1, y1, EndColor, x2, y2, Opacity); }
public ImageMenu() { this.Text = "메뉴 선택 표시와 이미지 넣기"; // 이미지 개체 준비 Bitmap bmp1 = new Bitmap(GetType(), "ImageMenu.image_1.bmp"); Bitmap bmp2 = new Bitmap(GetType(), "ImageMenu.image_2.bmp"); MenuStrip menu = new MenuStrip(); menu.Parent = this; // File 항목 ToolStripMenuItem file_item = new ToolStripMenuItem(); file_item.Text = "&File"; file_item.Image = bmp1; // 메뉴에 출력할 이미지 지정 menu.Items.Add(file_item); select_item = new ToolStripMenuItem(); select_item.Text = "&Select"; select_item.Click += EventProc; file_item.DropDownItems.Add(select_item); // 메뉴 구분선 넣기 ToolStripSeparator file_item_sep = new ToolStripSeparator(); file_item.DropDownItems.Add(file_item_sep); ToolStripMenuItem close_item = new ToolStripMenuItem(); close_item.Text = "&Close"; close_item.Image = bmp2; close_item.ShortcutKeys = Keys.Alt | Keys.F4; close_item.Click += EventProc; file_item.DropDownItems.Add(close_item); }
public async Task GetNewFrameAndApplyEffect(IBuffer frameBuffer, Size frameSize) { if (_semaphore.WaitOne(500)) { var scanlineByteSize = (uint)frameSize.Width * 4; // 4 bytes per pixel in BGRA888 mode var bitmap = new Bitmap(frameSize, ColorMode.Bgra8888, scanlineByteSize, frameBuffer); if (_filterEffect != null) { var renderer = new BitmapRenderer(_filterEffect, bitmap); await renderer.RenderAsync(); } else if (_customEffect != null) { var renderer = new BitmapRenderer(_customEffect, bitmap); await renderer.RenderAsync(); } else { var renderer = new BitmapRenderer(_cameraPreviewImageSource, bitmap); await renderer.RenderAsync(); } _semaphore.Release(); } }
public Bitmap GenerateBarcodeImage(string text, FontFamily fontFamily, int fontSizeInPoints) { StringBuilder sb = new StringBuilder(); sb.Append("*"); sb.Append(text); sb.Append("*"); Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb); Font font = new Font(fontFamily, fontSizeInPoints, FontStyle.Regular, GraphicsUnit.Point); Graphics graphics = Graphics.FromImage(bmp); SizeF textSize = graphics.MeasureString(sb.ToString(), font); bmp = new Bitmap(bmp, textSize.ToSize()); graphics = Graphics.FromImage(bmp); graphics.Clear(Color.White); graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; graphics.DrawString(sb.ToString(), font, new SolidBrush(Color.Black), 0, 0); graphics.Flush(); font.Dispose(); graphics.Dispose(); return bmp; }
/// <summary> /// ����ͼƬ /// </summary> /// <param name="checkCode">�����</param> private void CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 11.5);//����������趨ͼƬ��� Bitmap image = new Bitmap(iwidth, 20);//����һ������ Graphics g = Graphics.FromImage(image);//�ڻ����϶����ͼ��ʵ�� Font f = new Font("Arial",10,FontStyle.Bold);//���壬��С����ʽ Brush b = new SolidBrush(Color.Black);//������ɫ //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(Color.White);//������ɫ g.DrawString(checkCode, f, b, 3, 3); Pen blackPen = new Pen(Color.Black, 0); Random rand = new Random(); /*����� for (int i = 0; i < 5; i++) { int y = rand.Next(image.Height); g.DrawLine(blackPen, 0, y, image.Width, y); } */ System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); }
//Función que convierte una imagen a escala de grises public void convertirGris(string imagefrom, string imageto) { //create a blank bitmap the same size as original Bitmap original = new Bitmap(imagefrom); Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix(new float[][] { new float[] {.30f, .30f, .30f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); newBitmap.Save(imageto); }
protected virtual void Get_PANEL_Image(out Bitmap bac) { bac = new Bitmap(PANEL); BitmapData data_bac=bac.GetBitmapData(); Draw_PANEL_Image(data_bac); bac.UnlockBits(data_bac); }
public static bool Invert(Bitmap b) { // GDI+ still lies to us - the return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; unsafe { byte* p = (byte*)(void*)Scan0; int nOffset = stride - b.Width * 3; int nWidth = b.Width * 3; for (int y = 0; y < b.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = (byte)(255 - p[0]); ++p; } p += nOffset; } } b.UnlockBits(bmData); return true; }
public void Load(string exampleDir, Bitmap spriteSheet) { asteroidBitmap = spriteSheet; sprites = new List<Sprite>(); spriteSize = new Vector2(SpriteWidth, SpriteHeight); size = 1.0f; angle = 0.0f; Sprite newSprite; //Creo 64 sprites asignando distintos clipping rects a cada uno. for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { newSprite = new Sprite(); newSprite.Bitmap = asteroidBitmap; newSprite.SrcRect = new Rectangle(j * (int)spriteSize.X, i * (int)spriteSize.Y, (int)spriteSize.X, (int)spriteSize.Y); newSprite.Scaling = new Vector2(size, size); newSprite.Rotation = angle; sprites.Add(newSprite); } } currentSprite = 0; GenerateRandomPosition(); }
protected void Page_Load(object sender, EventArgs e) { int x, y; string strValidation = null; rnd = new Random(); Response.ContentType = "image/jpeg"; Response.Clear(); Response.BufferOutput = true; strValidation = GenerateString(); Session["strValidation"] = strValidation; Font font = new Font("Arial", (float)rnd.Next(17, 20)); Bitmap bitmap = new Bitmap(200, 50); Graphics gr = Graphics.FromImage(bitmap); gr.FillRectangle(Brushes.LightGreen, new Rectangle(0, 0, bitmap.Width, bitmap.Height)); gr.DrawString(strValidation, font, Brushes.Black, (float)rnd.Next(70), (float)rnd.Next(20)); // gr.DrawLine(new Pen(Color.White), new Point(0, rnd.Next(50)), new Point(200, rnd.Next(50))); // gr.DrawLine(new Pen(Color.White), new Point(0, rnd.Next(50)), new Point(200, rnd.Next(50))); // gr.DrawLine(new Pen(Color.White), new Point(0, rnd.Next(50)), new Point(200, rnd.Next(50))); for (x = 0; x < bitmap.Width; x++) for (y = 0; y < bitmap.Height; y++) if (rnd.Next(4) == 1) bitmap.SetPixel(x, y, Color.LightGreen); font.Dispose(); gr.Dispose(); bitmap.Save(Response.OutputStream, ImageFormat.Jpeg); bitmap.Dispose(); }
/// <summary> /// Capture the AutoCAD window now, returning the path of the file saved /// </summary> /// <returns></returns> public String CaptureNow() { if (InitGeometryReflectionInfo()) update_display.Invoke(null, new object[]{}); IntPtr main_window = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; RECT rect; GetWindowRect(main_window, out rect); int width = (int)(rect.Right - rect.Left); int height = (int)(rect.Bottom - rect.Top); string filename = BuildFileName(); using (Bitmap image = new Bitmap(width, height)) { Graphics g = Graphics.FromImage(image); g.CopyFromScreen((int)(rect.Left), (int)(rect.Top), 0, 0, new System.Drawing.Size(width, height)); image.Save(filename); } counter++; return filename; }
public static void LoadTexture() { Bitmap bitmap=null; BitmapData bitmapData=null; string[] tx={"relojes.bmp","ford1.bmp","benz1.jpg","motor.bmp","acelera.bmp","papel1.jpg","piso.jpg","madera2.jpg","madera3.jpg","papel1.jpg","Focus.jpg","fordrunner.jpg","mbne.jpg","particle.bmp","benz.jpg"}; Gl.glEnable(Gl.GL_TEXTURE_2D); Gl.glEnable(Gl.GL_DEPTH_TEST); // Gl.gl.Gl.glEnable(Gl.gl.Gl.gl_BLEND); // Gl.gl.Gl.glBlendFunc(Gl.gl.Gl.gl_SRC_ALPHA,Gl.gl.Gl.gl_ONE_MINUS_SRC_ALPHA); Rectangle rect; texture=new int[tx.Length]; Gl.glGenTextures(tx.Length, texture); for(int i=0; i<tx.Length; i++) { bitmap = new Bitmap(Application.StartupPath + "\\" + "Textures\\"+tx[i]); rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); bitmapData =bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture[i]); Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, (int) Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR_EXT, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0); } Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); Gl.glTexEnvf(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_DECAL); Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); bitmap.UnlockBits(bitmapData); bitmap.Dispose(); }
/// <summary> /// BitMap转换成二进制 /// </summary> /// <param name="bitmap"></param> /// <returns></returns> public static byte[] BitMapToByte(Bitmap bitmap) { //List<byte[]> list = new List<byte[]>(); MemoryStream ms = null; byte[] imgData = null; ///重新绘图并指定大小 int destWidth = 794; int destHight = 1122; Bitmap newBitmap = new Bitmap(destWidth, destHight); using(Graphics g=Graphics.FromImage((Image)newBitmap)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.AntiAlias; g.CompositingQuality = CompositingQuality.HighQuality; g.DrawImage((Image)bitmap, 0, 0, destWidth, destHight); g.Dispose(); } /// using (ms = new MemoryStream()) { newBitmap.Save(ms, ImageFormat.Jpeg); ms.Position = 0; imgData = new byte[ms.Length]; ms.Read(imgData, 0, Convert.ToInt32(ms.Length)); ms.Flush(); } //list.Add(imgData); return imgData; }
private void CreateImage() { Session["captcha.guid"] = Guid.NewGuid().ToString ("N"); string code = GetRandomText(); Bitmap bitmap = new Bitmap(WIDTH,HEIGHT,System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bitmap); Pen pen = new Pen(Color.DarkSlateGray); Rectangle rect = new Rectangle(0,0,WIDTH,HEIGHT); SolidBrush background = new SolidBrush(Color.AntiqueWhite); SolidBrush textcolor = new SolidBrush(Color.DarkSlateGray); int counter = 0; g.DrawRectangle(pen, rect); g.FillRectangle(background, rect); for (int i = 0; i < code.Length; i++) { g.DrawString(code[i].ToString(), new Font("Verdana", 10 + rand.Next(6, 14)), textcolor, new PointF(10 + counter, 10)); counter += 25; } DrawRandomLines(g); bitmap.Save(Response.OutputStream,ImageFormat.Gif); g.Dispose(); bitmap.Dispose(); }
/// <summary> Sets the bitmap that contains the bitmapped font characters as an atlas. </summary> public void SetFontBitmap( Bitmap bmp ) { FontBitmap = bmp; boxSize = FontBitmap.Width / 16; fontPixels = new FastBitmap( FontBitmap, true, true ); CalculateTextWidths(); }
protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; Bitmap bmp = new Bitmap("back.jpg"); Rectangle r = new Rectangle(0, 0, bmp.Width, bmp.Height); g.DrawImage(bmp, r, r, GraphicsUnit.Pixel); }
public string ReSizeImage(string imagePath, string outputPath, int newWidth) { System.Drawing.Image bm = System.Drawing.Image.FromFile(imagePath); string ext = Path.GetExtension(imagePath); string fileN = Path.GetFileName(imagePath); var imgFor = GetFormat(ext); int NewHeight = (bm.Height*newWidth)/bm.Width; Bitmap resized = new Bitmap(newWidth, NewHeight); Graphics g = Graphics.FromImage(resized); g.DrawImage(bm, new Rectangle(0, 0, resized.Width, resized.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel); g.Dispose(); bm.Dispose(); if (imgFor != null) { resized.Save(outputPath + fileN, imgFor); return outputPath + fileN; } else { return null; } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; string url = context.Request.RawUrl; string path = context.Request.MapPath(url); using (Image priImg = Image.FromFile(path)) { int width = 660; int height = 350; if (priImg.Width > priImg.Height) { height = width * priImg.Height / priImg.Width; } else { width = height * priImg.Width / priImg.Height; } path = context.Request.MapPath("logo.png"); using (Image logo = Image.FromFile(path)) { using (Bitmap bm = new Bitmap(width, height)) { using (Graphics g = Graphics.FromImage(bm)) { g.DrawImage(priImg, 0, 0, bm.Width, bm.Height); g.DrawImage(logo, bm.Width - logo.Width, bm.Height - logo.Height, logo.Width, logo.Height); bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } } }
public Bitmap generateTicket(string ticketType, string start, string destination, string price) { //Orte der verschiedenen Textboxen auf dem Ticket: Point StartLine1 = new Point(0,100); Point EndLine1 = new Point(960, 100); Point StartLine2 = new Point(0, 700); Point EndLine2 = new Point(960, 700); PointF logoLocation = new PointF(150,20); PointF fromLocation = new PointF(40,300); PointF toLocation = new PointF(40,500); PointF totalLocation = new PointF(40,750); PointF ticketTypeLocation = new PointF(40, 150); PointF startLocation = new PointF(40, 400); PointF destinationLocation = new PointF(40, 600); PointF priceLocation = new PointF(500, 750); //string imageFilePath = "C:\\Users\\kuehnle\\Documents\\TestWebsite\\NewTestTicket.bmp"; Bitmap tempBmp = new Bitmap(960,900); //auf das neu erstellte Bitmap draufzeichnen: using (Graphics g = Graphics.FromImage(tempBmp)) { g.Clear(Color.White); g.DrawLine(new Pen(Brushes.Black,10), StartLine1, EndLine1); g.DrawLine(new Pen(Brushes.Black,10), StartLine2, EndLine2); using (Font arialFont = new Font("Arial", 40,FontStyle.Bold)) { g.DrawString("Jakarta Commuter Train", arialFont, Brushes.Black, logoLocation); g.DrawString(ticketType, arialFont, Brushes.Black, ticketTypeLocation); } using (Font arialFont = new Font("Arial", 40, FontStyle.Underline)) { g.DrawString("From:", arialFont, Brushes.Black, fromLocation); g.DrawString("To:", arialFont, Brushes.Black, toLocation); } using (Font arialFont = new Font("Arial", 40, FontStyle.Regular)) { g.DrawString("Total:", arialFont, Brushes.Black, totalLocation); g.DrawString(start, arialFont, Brushes.Black, startLocation); g.DrawString(destination, arialFont, Brushes.Black, destinationLocation); g.DrawString(price, arialFont, Brushes.Black, priceLocation); } } //Farbtiefe auf 1 reduzieren: Bitmap ticket = tempBmp.Clone(new Rectangle(0, 0, tempBmp.Width, tempBmp.Height),PixelFormat.Format1bppIndexed); //ticket.Save(imageFilePath,System.Drawing.Imaging.ImageFormat.Bmp); //ticket.Dispose(); return ticket; }
//生成图像 private void getImageValidate(string strValue) { //string str = "OO00"; //前两个为字母O,后两个为数字0 int width = Convert.ToInt32(strValue.Length * 12); //计算图像宽度 Bitmap img = new Bitmap(width, 23); Graphics gfc = Graphics.FromImage(img); //产生Graphics对象,进行画图 gfc.Clear(Color.White); drawLine(gfc, img); //写验证码,需要定义Font Font font = new Font("arial", 12, FontStyle.Bold); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Blue, 1.5f, true); gfc.DrawString(strValue, font, brush, 3, 2); drawPoint(img); gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1); //将图像添加到页面 MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //更改Http头 Response.ClearContent(); Response.ContentType = "image/gif"; Response.BinaryWrite(ms.ToArray()); //Dispose gfc.Dispose(); img.Dispose(); Response.End(); }
public decimal eval_a(Bitmap A_0, decimal A_1) { while (true) { decimal num = eval_be.eval_a(A_0, eval_i.eval_a); int num2 = 4; while (true) { switch (num2) { case 0: if (true) { } num2 = 7; continue; case 1: return A_1; case 2: if (num < 0m) { num2 = 1; continue; } return num; case 3: num = eval_be.eval_a(A_0, eval_i.eval_b); num2 = 5; continue; case 4: if (num < 0m) { num2 = 0; continue; } return num; case 5: if (num < A_1) { num2 = 6; continue; } goto IL_5F; case 6: return A_1; case 7: if (eval_i.eval_b != null) { num2 = 3; continue; } goto IL_5F; } break; IL_5F: num2 = 2; } } return A_1; }
public static UIImage Filter(UIImage img, int puzzleSize) { int tileSize = 2; int paletteColorsNumber = BasePaletteColorsNumber + (8 * puzzleSize / 64); // 1/ Get the main colors // So we have a color palette Logger.I ("Filter: getting palette..."); var colorPalette = getColorPalette (img, paletteColorsNumber); // 1/ Resize & Load image as readable UIImage resizedImg = UIImageEx.ResizeRatio (img, puzzleSize); Bitmap bitmap = new Bitmap (resizedImg); // 2/ Apply mosaic Logger.I ("Filter: applying mosaic..."); var flippedImage = applyMosaic (tileSize, colorPalette, resizedImg, bitmap); // -- Flip because bitmap has inverted coordinates Logger.I ("Filter: resizing..."); UIImage finalImg = new UIImage (flippedImage, 0f, UIImageOrientation.DownMirrored); // UIImage finalImg = new UIImage (flippedImage); // -- Resize the final // return ResizeRatio (finalImg, FinalSize); Logger.I ("Filter: image ready!"); return finalImg; }
public void UpdateBitmaps(string name) { if (Directory.Exists(tempPath + "Okiaros")) { foreach (string currFile in Directory.GetFiles(tempPath + "Okiaros")) { File.Delete(currFile); } } else { Directory.CreateDirectory(tempPath + "Okiaros"); } string[] pngs = new string[Bitmaps.Count]; for (int i = 0; i < pngs.Length; i++) { pngs[i] = name + @"\texture-" + i.ToString("d3") + ".png"; } for (int i = 0; i < Bitmaps.Count; i++) { FileStream cFS = new FileStream(pngs[i], System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); Bitmaps[i] = new Bitmap(cFS); cFS.Close(); } var palettes = new List <string>(0); var toQuant = new List <Bitmap>(0); var filenames = new List <string>(0); for (int i = 0; i < paletteAddresses.Count; i++) { if (!palettes.Contains(paletteAddresses[i].ToString("X"))) { toQuant.Add(Bitmaps[i]); palettes.Add(paletteAddresses[i].ToString("X")); filenames.Add(paletteAddresses[i].ToString() + "@" + textureAddresses[i].ToString() + ",0,0," + Bitmaps[i].Width.ToString() + "," + Bitmaps[i].Height.ToString()); } else { for (int k = 0; k < paletteAddresses.Count; k++) { if (paletteAddresses[i].ToString() == paletteAddresses[k].ToString()) { int wi = toQuant[k].Width; int he = toQuant[k].Height; if (Bitmaps[i].Height > he) { he = Bitmaps[i].Height; } wi = wi + Bitmaps[i].Width; var merge = new Bitmap(wi, he); var mergeGr = Graphics.FromImage(merge); mergeGr.DrawImage(toQuant[k], new Rectangle(0, 0, toQuant[k].Width, toQuant[k].Height)); mergeGr.DrawImage(Bitmaps[i], new Rectangle(toQuant[k].Width, 0, Bitmaps[i].Width, Bitmaps[i].Height)); filenames[k] = filenames[k] + "@" + textureAddresses[i].ToString() + "," + toQuant[k].Width.ToString() + ",0," + Bitmaps[i].Width.ToString() + "," + Bitmaps[i].Height.ToString(); toQuant[k] = merge; k = paletteAddresses.Count; } } } } pngs = Directory.GetFiles(tempPath + "Okiaros", "*.png"); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "pngquant.exe"; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.Arguments = "pngquant.exe "; string[] toQuantFilenames = new string[toQuant.Count]; for (int i = 0; i < toQuant.Count; i++) { toQuantFilenames[i] = tempPath + @"Okiaros\" + filenames[i]; startInfo.Arguments += "\"" + toQuantFilenames[i] + ".png" + "\" "; toQuant[i].Save(toQuantFilenames[i] + ".png"); } Process.Start(startInfo); while (Process.GetProcessesByName("pngquant").Length > 0) { } for (int i = 0; i < toQuantFilenames.Length; i++) { File.Delete(toQuantFilenames[i] + ".png"); toQuantFilenames[i] += "-fs8.png"; } for (int g = 0; g < toQuantFilenames.Length; g++) { string curr = toQuantFilenames[g]; string filename_ = Path.GetFileName(curr).Split('-')[0]; string[] bounds = filename_.Split('@'); int newPaletteAddress = (int)(int.Parse(bounds[0])); var stream = new System.IO.FileStream(curr, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); var bitm2Palette = new Bitmap(stream); var decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); var bitmapSource = decoder.Frames[0]; var palette = new List <System.Windows.Media.Color>(bitmapSource.Palette.Colors); while (palette.Count < 256) { palette.Add(System.Windows.Media.Colors.Black); } /*if (checkBox1.Checked) * palette.Sort((System.Windows.Media.Color left, System.Windows.Media.Color right) => (BrightNess(left)).CompareTo(BrightNess(right)));*/ for (int c = 0; c < 256; c++) { int colorSlot = ((64 * ((c / 8) % 2) + ((c / 32) * 128) + (8 * ((c / 16) % 2)) + (c % 8)) * 4); if (colorSlot < timBinary.Buffer.Length - 3) { timBinary.Buffer[newPaletteAddress + colorSlot] = (byte)palette[c].R; timBinary.Buffer[newPaletteAddress + colorSlot + 1] = (byte)palette[c].G; timBinary.Buffer[newPaletteAddress + colorSlot + 2] = (byte)palette[c].B; timBinary.Buffer[newPaletteAddress + colorSlot + 3] = (byte)((palette[c].A + 1) / 2); } } for (int i = 1; i < bounds.Length; i++) { string[] splited = bounds[i].Split(','); int pixAddress = (int)(int.Parse(splited[0])); Bitmap CropBitmap = bitm2Palette.Clone(new Rectangle(int.Parse(splited[1]), int.Parse(splited[2]), int.Parse(splited[3]), int.Parse(splited[4])), System.Drawing.Imaging.PixelFormat.Format32bppArgb); LockBitmap CropBitmapLK = new LockBitmap(CropBitmap); CropBitmapLK.LockBits(); if (dmyCount > 0 && pixAddress >= DMY) { for (ushort x = 0; x < CropBitmap.Width; x++) { for (ushort y = 0; y < CropBitmap.Height; y++) { System.Windows.Media.Color currCol = CropBitmapLK.GetPixel(x, y); int pos = pixAddress + (y * CropBitmap.Width) + x; if (pos > timBinary.Buffer.Length - 1) { pos = timBinary.Buffer.Length - 1; } timBinary.Buffer[pos] = (byte)palette.IndexOf(currCol); //433 } } } else { int textW2 = (CropBitmap.Width * 2); int textW4 = (CropBitmap.Width * 4); for (int x = 0; x < CropBitmap.Width; x++) { ushort xMOD16 = (ushort)(x % 16); ushort xMOD8 = (ushort)(x % 8); ushort xOVER16 = (ushort)(x / 16); for (int y = 0; y < CropBitmap.Height; y++) { System.Windows.Media.Color currCol = CropBitmapLK.GetPixel(x, y); ushort yOVER4 = (ushort)(y / 4); ushort yMOD2 = (ushort)(y % 2); ushort yMOD4 = (ushort)(y % 4); ushort yMOD8 = (ushort)(y % 8); int offset = 32 * (xOVER16) + (4 * (xMOD16)) - (30 * ((xMOD16) >> 3)) + ((System.Byte)(y & 1)) * textW2 + ((System.Byte)(y >> 2)) * textW4 + ((((System.Byte)(y & 3)) >> 1) + (((xMOD8) >> 2) * -1 + (1 - ((xMOD8) >> 2))) * 16 * (((System.Byte)(y & 3)) >> 1) + (((xMOD8) >> 2) * -1 + (1 - ((xMOD8) >> 2))) * 16 * (((System.Byte)(y & 7)) >> 2)) * (1 - (((System.Byte)(y & 7)) >> 2) * (((System.Byte)(y & 3)) >> 1)) + (((System.Byte)(y & 7)) >> 2) * (((System.Byte)(y & 3)) >> 1); if (pixAddress + offset < timBinary.Buffer.Length) { timBinary.Buffer[pixAddress + offset] = (byte)palette.IndexOf(currCol); } } } } } stream.Close(); stream = null; decoder = null; bitmapSource = null; palette = null; toQuant = null; filenames = null; } }
public void SaveFace(string str, FaceRecognition rec) { try { BcFace bcFace = new BcFace(); string[] strArray = str.Replace(_currentDir + "\\", "").ToUpper().Replace(".JPEG", "").Replace(".JPG", "").Replace(".BMP", "").Replace(".GIF", "").Replace(".PNG", "").Replace(".TIFF", "").Split(new string[1] { " " }, StringSplitOptions.RemoveEmptyEntries); bcFace.Id = Guid.Empty; if (strArray.Length > 1) { bcFace.FirstName = strArray[1]; } if (strArray.Length > 0) { bcFace.Surname = strArray[0]; } if (strArray.Length > 2) { bcFace.LastName = strArray[2]; } Bitmap source = (Bitmap)Image.FromFile(str); TS.Sdk.StaticFace.Model.Image image = source.ConvertFrom(); BcKey bcKey = new BcKey(); FaceInfo face = rec.Engine.DetectMaxFace(image, null); if (face != null) { bcFace.Comment = CommonComment; bcFace.Sex = CommonSex; bcFace.AccessId = _selectedCategoryId; bcFace.EditUserId = MainForm.CurrentUser.Id; Rectangle faceRectangle = face.FaceRectangle; int width1 = (int)faceRectangle.Width * 2; faceRectangle = face.FaceRectangle; int height1 = (int)faceRectangle.Height * 2; Bitmap bitmap = new Bitmap(width1, height1); using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height); faceRectangle = face.FaceRectangle; double x1 = faceRectangle.X; faceRectangle = face.FaceRectangle; double num1 = faceRectangle.Width / 2.0; int x2 = (int)(x1 - num1); double num2 = source.Height; faceRectangle = face.FaceRectangle; double y1 = faceRectangle.Y; double num3 = num2 - y1; faceRectangle = face.FaceRectangle; double height2 = faceRectangle.Height; double num4 = num3 - height2; faceRectangle = face.FaceRectangle; double num5 = faceRectangle.Width / 2.0; int y2 = (int)(num4 - num5); int width2 = bitmap.Width; int height3 = bitmap.Height; graphics.DrawImage(source, new System.Drawing.Rectangle(0, 0, width2, height3), new System.Drawing.Rectangle(x2, y2, width2, height3), GraphicsUnit.Pixel); } MemoryStream memoryStream1 = new MemoryStream(); MemoryStream memoryStream2 = new MemoryStream(); bitmap.Save(memoryStream1, ImageFormat.Jpeg); BcImage bcImage = new BcImage(); if (bitmap.Width >= 300) { bitmap = new Bitmap(bitmap, new Size(bitmap.Width / 2, bitmap.Height / 2)); bitmap.Save(memoryStream2, ImageFormat.Jpeg); bcFace.ImageIcon = memoryStream2.GetBuffer(); bcImage.ImageIcon = memoryStream2.GetBuffer(); } else { bcFace.ImageIcon = memoryStream1.GetBuffer(); bcImage.ImageIcon = memoryStream1.GetBuffer(); } bcFace.Save(); bcImage.FaceId = bcFace.Id; bcImage.Image = memoryStream1.GetBuffer(); bcImage.FaceId = bcFace.Id; bcImage.Save(); bitmap.Dispose(); memoryStream1.Close(); memoryStream1.Dispose(); memoryStream2.Close(); memoryStream2.Dispose(); bcKey.ImageKey = rec.Engine.ExtractTemplate(image, face); if (bcKey.ImageKey != null) { bcKey.Ksid = -1; bcKey.ImageId = bcImage.Id; bcKey.FaceId = bcFace.Id; bcKey.Save(); } else { Errors.Add("Error to create template"); ErrorFiles.Add(str); } } else { Errors.Add(Messages.NoFaceWasFound); ErrorFiles.Add(str); } source.Dispose(); } catch (Exception ex) { Errors.Add(ex.Message); ErrorFiles.Add(str); } rec.IsWork = false; try { Invoke(new NewValueFileFunc(NewValueFile), (object)_progVal, (object)_mainIndex, (object)_commonFiles.Count); } catch { } }
private void button4_Click(object sender, EventArgs e) { int x = 0; int y = 0; int width = 1; int height = 1; int r = 0; int g = 0; int b = 0; int a = 255; int max = 256; Graphics g1 = null; Graphics g2 = null; Graphics g3 = null; Graphics gp1 = null; Graphics gp2 = null; Graphics gp3 = null; Brush brush = null; Bitmap b1 = new Bitmap(256, 256); Bitmap b2 = new Bitmap(256, 256); Bitmap b3 = new Bitmap(256, 256); try { g1 = Graphics.FromImage(b1); g2 = Graphics.FromImage(b2); g3 = Graphics.FromImage(b3); for (r = 0; r < max; r++) { for (g = 0; g < max; g++) { x = g; y = r; brush = new SolidBrush(Color.FromArgb(a, r, g, b)); g1.FillRectangle(brush, x, y, width, height); } } gp1 = panel1.CreateGraphics(); gp1.DrawImage(b1, new Point(0, 0)); r = 0; for (g = 0; g < max; g++) { for (b = 0; b < max; b++) { x = b; y = g; brush = new SolidBrush(Color.FromArgb(a, r, g, b)); g2.FillRectangle(brush, x, y, width, height); } } gp2 = panel2.CreateGraphics(); gp2.DrawImage(b2, new Point(0, 0)); g = 0; for (b = 0; b < max; b++) { for (r = 0; r < max; r++) { x = r; y = b; brush = new SolidBrush(Color.FromArgb(a, r, g, b)); g3.FillRectangle(brush, x, y, width, height); } } gp3 = panel3.CreateGraphics(); gp3.DrawImage(b3, new Point(0, 0)); } finally { gp1.Dispose(); gp2.Dispose(); gp3.Dispose(); g1.Dispose(); g2.Dispose(); g3.Dispose(); } }
private static Bitmap transformCustomButtonIcon(Bitmap bmp, string field, int i) => Dpi.ScalePercent > 100 ? bmp.HalfResizeDpi() : bmp.ResizeDpi();
public ActionResult LogoFoto(int ContratanteId, HttpPostedFileBase file) { ViewBag.ContratanteID = ContratanteId; int grupoId = (int)Geral.PegaAuthTicket("Grupo"); int usuarioId = (int)Geral.PegaAuthTicket("UsuarioId"); if (file == null) { ModelState.AddModelError("", "Escolha uma Imagem!"); } else { MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); Bitmap imagem1 = (Bitmap)Image.FromStream(target); Bitmap imagemRedimensionada = ScaleImage(imagem1, 220, 130); MemoryStream novaImagem = new MemoryStream(); imagemRedimensionada.Save(novaImagem, System.Drawing.Imaging.ImageFormat.Png); Contratante contratante = Db.Contratante.FirstOrDefault(c => c.WFD_GRUPO.Any(g => g.ID == grupoId)); if (contratante != null) { contratante.LOGO_FOTO = novaImagem.ToArray(); //string extensao = (file.FileName.IndexOf(".") >= 0) ? file.FileName.Substring(file.FileName.IndexOf(".")) : ""; contratante.EXTENSAO_IMAGEM = ".png"; Db.Entry(contratante).State = EntityState.Modified; } Db.SaveChanges(); string caminhoFisico = Server.MapPath("/ImagensUsuarios"); string arquivo = "ImagemContratante" + contratante.ID + ".png"; string caminhoCompleto = caminhoFisico + "\\" + arquivo; System.IO.File.WriteAllBytes(caminhoCompleto, novaImagem.ToArray()); string dados = User.Identity.Name; dados = dados.Replace("semfoto.png", arquivo).Replace("semlogo.png", arquivo); var usuario = Db.WFD_USUARIO .Include("WAC_PERFIL.WAC_FUNCAO") .FirstOrDefault(u => u.ID == usuarioId); string roles = string.Empty; foreach (var perfil in usuario.WAC_PERFIL) { foreach (var funcao in perfil.WAC_FUNCAO) { if (!roles.Contains(funcao.CODIGO)) { roles += funcao.CODIGO + ","; } } } _metodosGerais.CriarAuthTicket(dados, roles); _metodosGerais.AuthenticateRequest(); ViewBag.MensagemSucesso = "Imagem Salva com sucesso!"; } return(View()); }
public static IntPtr NativeHandle(this Bitmap Bmp) { return Bmp.GetPrivateField<IntPtr>("nativeImage"); }
public static void ChangeTo32bppARGB(this Bitmap Bmp) { GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format32bppArgb), DitherType.DitherTypeNone, PaletteType.PaletteTypeCustom, IntPtr.Zero, 50f); }
public static void ChangeTo16bppRgb555(this Bitmap Bmp, DitherType ditherType = DitherType.DitherTypeErrorDiffusion) { GdipBitmapConvertFormat(Bmp.NativeHandle(), Convert.ToInt32(PixelFormat.Format16bppRgb555), ditherType, PaletteType.PaletteTypeCustom, IntPtr.Zero, 50f); }
private void GameFormMode2_Paint(object sender, PaintEventArgs e) { if (next_game_shown) { AnotherGame.Show(); } else { AnotherGame.Hide(); } // map block id to its color foreach (Block block in this.settings.blocks) { if (!idcolor_map.ContainsKey(block.id)) { idcolor_map.Add(block.id, block.color); } } Control control = (Control)sender; int local_indentX = INDENT_X + (settings.cols * settings.cell_size) + settings.cell_size; int local_indentY = INDENT_Y; for (int i = 0; i < this.settings.cols; i++) { for (int j = 0; j < this.settings.rows; j++) { // draw playing area Pen blackPen = new Pen(Color.Black, 1); e.Graphics.DrawRectangle(blackPen, i * this.settings.cell_size + INDENT_X, j * this.settings.cell_size + INDENT_Y, this.settings.cell_size, this.settings.cell_size); // draw final state example area e.Graphics.DrawRectangle(blackPen, i * this.settings.cell_size + local_indentX, j * this.settings.cell_size + local_indentY, this.settings.cell_size, this.settings.cell_size); if (idcolor_map.ContainsKey(settings.playground[j, i])) { Color c = idcolor_map[settings.playground[j, i]]; Brush brush = new SolidBrush(c); e.Graphics.FillRectangle(brush, i * this.settings.cell_size + local_indentX, j * this.settings.cell_size + local_indentY, this.settings.cell_size, this.settings.cell_size); } } } // draw blocks last foreach (Block block in settings.blocks) { block.Kresli(e.Graphics); } if (showWin) { Graphics g = e.Graphics; Bitmap main_image = new Bitmap("smile.png"); next_game_shown = true; Color backColor = main_image.GetPixel(1, 1); main_image.MakeTransparent(backColor); e.Graphics.DrawImage( main_image, this.Width - 100, 0, 64, 64); } }
public Aprox(Aprox apx, Image orginal, int seed, int id) { Generation = apx.Generation++; rectangles = new List <Rectangle>(); brushes = new List <SolidBrush>(); r = new Random(seed); this.parentID = id; ShapeNum = apx.ShapeNum; ImageWidth = apx.ImageWidth; ImageHeight = apx.ImageHeight; madeImage = new Bitmap(ImageWidth, ImageHeight); // rectangles =apx.rectangles; rectangles.Clear(); foreach (Rectangle re in apx.rectangles) { rectangles.Add(new Rectangle(re.X, re.Y, re.Width, re.Height)); } // brushes = apx.brushes; brushes.Clear(); foreach (SolidBrush sb in apx.brushes) { brushes.Add(new SolidBrush(sb.Color)); } // modify int k; for (k = 0; k < 1 + r.Next(3); k++) { double tmp = r.NextDouble(); if (tmp < 0.33 || tmp > 0.98) { int IDMod = r.Next(ShapeNum - 1) + 1; if (r.NextDouble() > 0.2) { rectangles[IDMod] = ChangeRectangle(rectangles[IDMod], ImageWidth, ImageHeight, r); } else { int sw = r.Next(ImageWidth); int sh = r.Next(ImageHeight); rectangles[IDMod] = new Rectangle(sw, sh, r.Next(Math.Min(ImageWidth - sw, ImageWidth / 7)), r.Next(Math.Min(ImageHeight - sh, ImageHeight / 7))); } } if (tmp < 0.66 && tmp > 0.3) { int IDMod = r.Next(ShapeNum); if (r.NextDouble() > 0.8) { brushes[IDMod].Color = Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)); } else { brushes[IDMod].Color = ChangeColour(brushes[IDMod].Color, r); } } if (tmp > 0.6 || tmp < 0.02) { int IDMod1 = r.Next(ShapeNum - 1) + 1; int IDMod2 = r.Next(ShapeNum - 1) + 1; Rectangle tempR = rectangles[IDMod1]; SolidBrush tempB = brushes[IDMod1]; rectangles[IDMod1] = rectangles[IDMod2]; brushes[IDMod1] = brushes[IDMod2]; rectangles[IDMod2] = tempR; brushes[IDMod2] = tempB; } } int i; for (i = 0; i < ShapeNum; i++) { // int sw = r.Next(ImageWidth); // int sh = r.Next(ImageHeight); // rectangles.Add(new Rectangle(sw, sh, r.Next(ImageWidth - sw), r.Next(ImageHeight - sh))); // brushes.Add(new SolidBrush(Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)))); using (Graphics g = Graphics.FromImage(madeImage)) { g.FillRectangle(brushes[i], rectangles[i]); } } SetScore(orginal); }
public MapGraphics GetMapGraphics() { Bitmap bitmap = new Bitmap(new MemoryStream(GetImageBytes())); return(MapGraphics.FromImage(bitmap, _extent)); }
abstract public Bitmap SetAntialiasing(Bitmap bmp);
//Вывод всей информации public void Information() { listView1.Items.Clear(); //string path = Convert.ToString(Environment.CurrentDirectory);//Путь к папке с проектом string za = "select * from Service "; using (SqlConnection podkl = new SqlConnection(Server)) { podkl.Open(); inf1 = new DataSet(); sql = new SqlDataAdapter(za, podkl); sql.Fill(inf1); } int alln = Convert.ToInt32(inf1.Tables[0].Rows.Count);//Все значнения в базе //Вариации запроса поиска по фильтрам zap = "select * from Service "; if (y == true && x == true&& z == true)//Если выбраны все значения { Sale(); zap += " and Title like'"+textBox1.Text+ "%' order by Cost desc"; } else if(y == true && x == true)//Если выбраны скидка и цена { Sale(); zap += " order by Cost desc"; } else if (y == true && z == true)//Если выбраны скидка и текст { Sale(); zap += " and Title like'" + textBox1.Text + "%'"; } else if (x == true && z == true)//Если выбраны цена и текст { zap += " where Title like'" + textBox1.Text + "%' order by Cost desc"; } else if (y == true)//Если скидка Sale(); else if (z==true)//Если текст zap += " where Title like'"+textBox1.Text+"%'"; else if (x == false)//если цена zap += " order by Cost asc"; using (SqlConnection podkl = new SqlConnection(Server)) { podkl.Open(); inf = new DataSet(); sql = new SqlDataAdapter(zap, podkl); sql.Fill(inf); } n = Convert.ToInt32(inf.Tables[0].Rows.Count);//кол-во выведенных товаров label1.Text = "Кол-во предоженных услуг " + n + " из " + alln; ImageList image = new ImageList(); image.ImageSize = new Size(150, 150); //Цикл записывающий фото из бд в лист for (int i = 0; i < n; i++) { photo =inf.Tables[0].Rows[i]["MainImagePath"].ToString(); image.Images.Add(new Bitmap(photo)); //if (photo != "") //{ // int result = String.Compare(path, photo); // if (result < 0) // { // image.Images.Add(new Bitmap(photo)); // } // else // { // photo = path + "\\" + photo; // image.Images.Add(new Bitmap(photo)); // } //} } Bitmap img = new Bitmap(150, 150); image.Images.Add(img); listView1.SmallImageList = image; mas_sale = new int[n]; mas_price = new int[n]; mas_price_sale = new int[n]; chas = new string[n]; min = new string[n]; //Скидка for (int i = 0; i < n; i++) { price = Convert.ToInt32(inf.Tables[0].Rows[i]["Cost"]); mas_price[i] += price; if (inf.Tables[0].Rows[i]["Discount"].ToString() != "") { sale = Convert.ToInt32(inf.Tables[0].Rows[i]["Discount"]); mas_sale[i] += sale; price -= (price / 100 * sale); mas_price_sale[i] += price; } } //Время for (int i = 0; i < n; i++) { int mins,h; sec = Convert.ToInt32(inf.Tables[0].Rows[i]["DurationInSeconds"]); mins = sec / 60; if (mins >= 60) { h = mins / 60; mins = mins % 60; chas[i] += Convert.ToString(h) + " " + "ч "; } min[i] += Convert.ToString(mins) + " " + "мин"; } //Занесение в список for (int i = 0; i < n; i++) { ListViewItem list; //Записи где есть скидка if (mas_sale[i] != 0) { //Занесение всех записей list = new ListViewItem(new string[] {"", name= inf.Tables[0].Rows[i]["Title"].ToString(), mas_price[i].ToString(), mas_price_sale[i].ToString(), mas_sale[i].ToString(), chas[i]+" "+ min[i] }); //Применение стилей для текста с ценой Font f = new Font("Comic Sans MS", 10, FontStyle.Strikeout); list.SubItems[2].Font = f;//стиль текста Font f1 = new Font("Comic Sans MS", 12, FontStyle.Bold); list.SubItems[3].Font = f1;//стиль текста for (int j = 0; j < listView1.Columns.Count; j++) { list.SubItems[j].BackColor = Color.FromArgb(179, 247, 111); } list.UseItemStyleForSubItems = false;//применение стиля отдельно для каждой ячейки } else { list = new ListViewItem(new string[] {"", name= inf.Tables[0].Rows[i]["Title"].ToString(), mas_price[i].ToString(),"","", chas[i]+" "+ min[i] }); } list.ImageIndex = i; listView1.Items.Add(list); } }
//表單載入時執行 private void Form1_Load(object sender, EventArgs e) { bmp = new Bitmap(345, 270); picDraw.BackColor = Color.White; p = new Pen(Color.Black, 2); //指定畫筆的顏色與粗細 }
public void BehaviorAutoSize () { if (TestHelper.RunningOnUnix) Assert.Ignore ("Depends on font measurements, corresponds to windows"); Form f = new Form (); f.ShowInTaskbar = false; f.Show (); Image i = new Bitmap (20, 20); String s = "My test string"; Button b = new Button (); Size s_size = TextRenderer.MeasureText (s, new Button ().Font); b.UseCompatibleTextRendering = false; b.AutoSize = true; b.AutoSizeMode = AutoSizeMode.GrowAndShrink; b.Text = s; f.Controls.Add (b); // Text only b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + 10), b.Size, "A1"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + 10), b.Size, "A2"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + 10), b.Size, "A3"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + 10), b.Size, "A4"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + 10), b.Size, "A5"); // Text and Image b.Image = i; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual (new Size (s_size.Width + 10, i.Height + 6), b.Size, "A6"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + i.Height + 10), b.Size, "A7"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual (new Size (s_size.Width + i.Width + 10, i.Height + 6), b.Size, "A8"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual (new Size (s_size.Width + 10, s_size.Height + i.Height + 10), b.Size, "A9"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual (new Size (s_size.Width + i.Width + 10, i.Height + 6), b.Size, "A10"); // Image only b.Text = string.Empty; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual (new Size (i.Height + 6, i.Height + 6), b.Size, "A11"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual (new Size (i.Height + 6, i.Height + 6), b.Size, "A12"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual (new Size (i.Height + 6, i.Height + 6), b.Size, "A13"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual (new Size (i.Height + 6, i.Height + 6), b.Size, "A14"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual (new Size (i.Height + 6, i.Height + 6), b.Size, "A15"); // Neither b.Image = null; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual (new Size (6, 6), b.Size, "A16"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual (new Size (6, 6), b.Size, "A17"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual (new Size (6, 6), b.Size, "A18"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual (new Size (6, 6), b.Size, "A19"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual (new Size (6, 6), b.Size, "A20"); // Padding b.Padding = new Padding (5, 10, 15, 20); Assert.AreEqual (new Size (6 + b.Padding.Horizontal, 6 + b.Padding.Vertical), b.Size, "A21"); f.Dispose (); }
} ///< Returns a static white texture. /// <summary> /// Creates an image from a given Bitmap. /// </summary> /// <param name="bmp">Data source.</param> private ImageSource(Bitmap bmp) { _path = "[Blank]"; _rawImage = bmp; Texture = new Texture(Width, Height, bmp.GetPixels()); }
void renderText() { while (_run) { try { Bitmap im = new Bitmap(721, 363); Graphics g = Graphics.FromImage(im); g.Clear(Color.Transparent); List<BrailleIOViewRange> vrs = getAllViews(); foreach (var vr in vrs) { int x, y, width, height; if (vr != null && vr.ContentRender is ITouchableRenderer) { //get visible area in view Range; Rectangle r = vr.ViewBox; Rectangle cb = vr.ContentBox; int left = -vr.GetXOffset(); int top = -vr.GetYOffset(); int right = left + cb.Width; int bottom = top + cb.Height; //get vr position on screen x = r.X + cb.X - left; y = r.Y + cb.Y - top; width = cb.Width; height = cb.Height; var items = getRenderingElementsFromViewRange(vr, left, right, top, bottom); List<RenderElement> elements = items as List<RenderElement>; if (items != null && items.Count > 0) { foreach (var e in elements) { getImageOfRenderingElement(e, ref g, x, y, left, right, top, bottom); } } } } g.Dispose(); //im = ChangeOpacity(im, 0.8f); if (monitor != null) { monitor.SetPictureOverlay(im); } } catch (System.Exception ex) { // return; continue; } finally { if (((ShowOff)this.monitor).IsDisposed) { _run = false; } else Thread.Sleep(200); } } System.Diagnostics.Debug.WriteLine("Thread beendet"); }
public void GetDisplayTextures() { if (this.Bitmaps.Count == 0) { return; } if (this.DisplayTextures.Length == 0) { this.DisplayTextures = new Microsoft.Xna.Framework.Graphics.Texture2D[Bitmaps.Count - Patches.Count]; this.EmptyPatches = new Bitmap[Patches.Count]; } for (int i = 0; i < this.EmptyPatches.Length; i++) { Bitmap img = this.Bitmaps[this.PatchTextureIndexes[i]].Clone(new Rectangle(0, 0, this.Bitmaps[this.PatchTextureIndexes[i]].Width, this.Bitmaps[this.PatchTextureIndexes[i]].Height), this.Bitmaps[this.PatchTextureIndexes[i]].PixelFormat); if (this.PatchIndexes[i] > -1) { Bitmap img2 = new Bitmap(img.Width, img.Height); Graphics img2Gr = Graphics.FromImage(img2); img2Gr.DrawImage(this.Patches[i], new Rectangle(this.PatchLocs[i].X, this.PatchLocs[i].Y, this.PatchSizes[i].Width, this.PatchSizes[i].Height), new Rectangle(0, this.PatchSizes[i].Height * this.PatchIndexes[i], this.PatchSizes[i].Width, this.PatchSizes[i].Height), GraphicsUnit.Pixel); Rectangle rect; if (this.PatchLocs[i].X > 0) { rect = new Rectangle(0, 0, this.PatchLocs[i].X, img.Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[i].Y > 0) { rect = new Rectangle(0, 0, img.Width, this.PatchLocs[i].Y); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[i].X + this.PatchSizes[i].Width < img.Width) { rect = new Rectangle(this.PatchLocs[i].X + this.PatchSizes[i].Width, 0, img.Width - this.PatchLocs[i].X - this.PatchSizes[i].Width, img.Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[i].Y + this.PatchSizes[i].Height < img.Height) { rect = new Rectangle(0, this.PatchLocs[i].Y + this.PatchSizes[i].Height, img.Width, img.Height - this.PatchLocs[i].Y - this.PatchSizes[i].Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } img = img2; } Graphics grPatch = Graphics.FromImage(img); grPatch.FillRectangle(new SolidBrush(Color.FromArgb(150, 0, 0, 0)), new Rectangle(0, 0, img.Width, img.Height - 1)); grPatch.FillRectangle(new SolidBrush(Color.FromArgb(100, 255, 100, 100)), new Rectangle(this.PatchLocs[i].X, this.PatchLocs[i].Y, this.PatchSizes[i].Width, this.PatchSizes[i].Height - 1)); grPatch.DrawRectangle(new Pen(Color.Red, 1), new Rectangle(this.PatchLocs[i].X, this.PatchLocs[i].Y, this.PatchSizes[i].Width, this.PatchSizes[i].Height - 1)); this.EmptyPatches[i] = img; } for (int i = 0; i < this.DisplayTextures.Length; i++) { Bitmap img = this.Bitmaps[i].Clone(new Rectangle(0, 0, this.Bitmaps[i].Width, this.Bitmaps[i].Height), this.Bitmaps[i].PixelFormat); for (int j = 0; j < this.PatchTextureIndexes.Count; j++) { if (this.PatchTextureIndexes[j] == i) { if (this.PatchIndexes[j] < 0) { continue; } Bitmap img2 = new Bitmap(img.Width, img.Height); Graphics img2Gr = Graphics.FromImage(img2); img2Gr.DrawImage(this.Patches[j], new Rectangle(this.PatchLocs[j].X, this.PatchLocs[j].Y, this.PatchSizes[j].Width, this.PatchSizes[j].Height), new Rectangle(0, this.PatchSizes[j].Height * this.PatchIndexes[j], this.PatchSizes[j].Width, this.PatchSizes[j].Height), GraphicsUnit.Pixel); Rectangle rect; if (this.PatchLocs[j].X > 0) { rect = new Rectangle(0, 0, this.PatchLocs[j].X, img.Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[j].Y > 0) { rect = new Rectangle(0, 0, img.Width, this.PatchLocs[j].Y); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[j].X + this.PatchSizes[j].Width < img.Width) { rect = new Rectangle(this.PatchLocs[j].X + this.PatchSizes[j].Width, 0, img.Width - this.PatchLocs[j].X - this.PatchSizes[j].Width, img.Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } if (this.PatchLocs[j].Y + this.PatchSizes[j].Height < img.Height) { rect = new Rectangle(0, this.PatchLocs[j].Y + this.PatchSizes[j].Height, img.Width, img.Height - this.PatchLocs[j].Y - this.PatchSizes[j].Height); img2Gr.DrawImage(img, rect, rect, GraphicsUnit.Pixel); } img = img2; } } this.DisplayTextures[i] = Tex2Dbmp.GetTexture2DFromBitmap(img); Bitmap imgHalfOp = new Bitmap(img.Width, img.Height); Graphics imgHalfGR = Graphics.FromImage(imgHalfOp); System.Drawing.Imaging.ColorMatrix cmxPic = new System.Drawing.Imaging.ColorMatrix(); cmxPic.Matrix33 = 0.333f; System.Drawing.Imaging.ImageAttributes iaPic = new System.Drawing.Imaging.ImageAttributes(); iaPic.SetColorMatrix(cmxPic, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap); imgHalfGR.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, iaPic); } }
private void save3D_button_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png|avi (*.avi)|*.avi"; foreach (DataGridViewRow row in dataGridView1.Rows) { try { if (row.Cells[3].Value.ToString() == "Video") { sfd.FileName = "Anaglyph_video"; AForge.Video.FFMPEG.VideoFileReader reader_left = new AForge.Video.FFMPEG.VideoFileReader(); AForge.Video.FFMPEG.VideoFileReader reader_right = new AForge.Video.FFMPEG.VideoFileReader(); reader_left.Open(row.Cells[0].Value.ToString()); reader_right.Open(row.Cells[1].Value.ToString()); int width = reader_left.Width; int height = reader_left.Height; int frameRate = reader_left.FrameRate; long frameCount = reader_left.FrameCount; string codecName = reader_left.CodecName; AForge.Video.FFMPEG.VideoFileWriter writer = new AForge.Video.FFMPEG.VideoFileWriter(); if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName.Length > 0) { string fileName = sfd.FileName; writer.Open(fileName, width, height, frameRate, AForge.Video.FFMPEG.VideoCodec.Default, 30); Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb); // write 1000 video frames for (int i = 0; i < (int)frameCount; i++) { try { Bitmap videoFrame_left = reader_left.ReadVideoFrame(); Bitmap videoFrame_right = reader_left.ReadVideoFrame(); Bitmap anaglyph_vid = mainForm.apply3D2(videoFrame_left, videoFrame_right, row.Cells[2].Value.ToString()); writer.WriteVideoFrame(anaglyph_vid); } catch (Exception ex) { } } writer.Close(); } } else { sfd.FileName = "Anaglyph_image"; string left = row.Cells[0].Value.ToString(); Bitmap left_save = new Bitmap(left); string right = row.Cells[1].Value.ToString(); Bitmap right_save = new Bitmap(right); string type = row.Cells[2].Value.ToString(); Bitmap ana_save = mainForm.apply3D2(left_save, right_save, row.Cells[2].Value.ToString()); if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName.Length > 0) { ana_save.Save(sfd.FileName); } } } catch (Exception ex) { } } }
public override void SetImageBitmap(Bitmap bm) { base.SetImageBitmap(bm); this.Initialize(); }
private void timer1_Tick(object sender, EventArgs e) { getTime = DateTime.Now.Hour; if (h == true) { if (getTime > 12) { getTime = getTime - 12; } if (getTime == 0) { getTime = 12; } } if (getTime > 9) { if (isLong != true) { if (DateTime.Now.Minute > 9) { label2.Text = getTime + ":" + DateTime.Now.Minute; } else { label2.Text = getTime + ":" + "0" + DateTime.Now.Minute; } } else { if (DateTime.Now.Minute > 9) { label2.Text = getTime + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second; } else { label2.Text = getTime + ":" + "0" + DateTime.Now.Minute + ":" + DateTime.Now.Second; } } } else { if (isLong != true) { if (DateTime.Now.Minute > 9) { label2.Text = "0" + getTime + ":" + DateTime.Now.Minute; } else { label2.Text = "0" + getTime + ":" + "0" + DateTime.Now.Minute; } } else { if (DateTime.Now.Minute > 9) { label2.Text = "0" + getTime + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second; } else { label2.Text = "0" + getTime + ":" + "0" + DateTime.Now.Minute + ":" + DateTime.Now.Second; } } } // if (clk == true) { label2.Hide(); g = this.CreateGraphics(); Time = (Bitmap)FancyText.ImageFromText(label2.Text, label2.Font, label2.ForeColor, stroke, blur); g.FillRectangle(SystemBrushes.Control, this.ClientRectangle); g.DrawImageUnscaled(Time, label2.Location); g.Dispose(); } else { label2.Show(); } // fRam = RamC.NextValue(); label1.Text = "Available memory: " + fRam.ToString() + "MB"; //label1.Hide(); // RAM = (Bitmap)FancyText.ImageFromText(label1.Text, label1.Font, Color.Black, Color.White); // g.FillRectangle(SystemBrushes.Control, label1.Bounds); // g.DrawImageUnscaled(RAM, label1.Location); // pDisk = Disk.NextValue(); pDisk2 = Math.Round(pDisk, 1); if (pDisk2 > 100) { pDisk2 = 100; } label3.Text = "Disk usage: " + pDisk2.ToString() + "%"; // label3.Hide(); //DISK = (Bitmap)FancyText.ImageFromText(label3.Text, label3.Font, Color.Black, Color.White); // g.FillRectangle(SystemBrushes.Control, label3.Bounds); // g.DrawImageUnscaled(DISK, label3.Location); // pCpu = Cpu.NextValue(); pCpu2 = Math.Round(pCpu, 1); label4.Text = "CPU usage: " + pCpu2.ToString() + "%"; //label4.Text = "CPU speed: " + (CPUSpeed()/1000).ToString() + "GHz"; // label4.Hide(); // CPU = (Bitmap)FancyText.ImageFromText(label4.Text, label4.Font, Color.Black, Color.White); // g.FillRectangle(SystemBrushes.Control, label4.Bounds); // g.DrawImageUnscaled(CPU, label4.Location); }
protected virtual SpriteFromSheet BuildSpriteSheet() { var ss = new SpriteSheet(); //Each action has 8 directions * actionCount sprites int spriteSheetId = 0; foreach (var animation in XGCharacter.RawAnimationsData) { FileInfo f = new FileInfo(Path.Combine(_spritesPath, animation.StartSprite)); for (int dir = 0; dir < 5; dir++) { int skip = animation.SkipBetweenFiles * dir; for (int num = 0; num < animation.Count; num++) { var spritePath = f.DirectoryName + "\\" + (Convert.ToInt32(Path.GetFileNameWithoutExtension(f.Name)) + ((dir * animation.Count) + num + skip)).ToString().PadLeft(4, '0') + ".png"; if (File.Exists(spritePath)) // Some sprites missing? { var bytes = File.ReadAllBytes(spritePath); var image = Stride.Graphics.Image.Load(bytes); var texture = Texture.New(this.GraphicsDevice, image, TextureFlags.ShaderResource); var sprite = new Sprite($"{animation.Name}_{dir}_{num}", texture); ss.Sprites.Add(sprite); var animationKey = (animation.Name, (ECameraDirection)dir); if (!this._animations.ContainsKey(animationKey)) { this._animations.Add(animationKey, new List <IndividualAnimation>()); } _animations[animationKey].Add(new IndividualAnimation() { Name = animation.Name, Count = animation.Count, Direction = (ECameraDirection)dir, Frame = num, SpriteSheetId = spriteSheetId++ }); if (dir > 0 && dir < 4) // Get non-north south sprites. Will use for mirror { var bitmap = new Bitmap(spritePath); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); bytes = BitmapToByteArray(bitmap); image = Stride.Graphics.Image.Load(bytes); texture = Texture.New(this.GraphicsDevice, image, TextureFlags.ShaderResource); sprite = new Sprite($"{animation.Name}_{dir}_{num}", texture); ss.Sprites.Add(sprite); animationKey = (animation.Name, (ECameraDirection)(8 - dir)); if (!this._animations.ContainsKey(animationKey)) { this._animations.Add(animationKey, new List <IndividualAnimation>()); } _animations[animationKey].Add(new IndividualAnimation() { Name = animation.Name, Count = animation.Count, Direction = (ECameraDirection)(8 - dir), Frame = num, SpriteSheetId = spriteSheetId++ }); } } } } } _previousAnimation = _animations[(EActionTypes.Idle, ECameraDirection.North)][0];
public UnsafeBitmap(int width, int height) { this.bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb); }
/// <summary> /// Converts an image to ascii with a defined line width, and writes to file /// </summary> /// <param name="inputFileName">Fullly qualified filename to any image file</param> /// <param name="outputFileName">Full path to dump the output text to</param> /// <param name="width">Width to scale the image to.</param> public static void ConvertToAscii(string inputFileName, string outputFileName, int width) { Bitmap b = new Bitmap(inputFileName); ConvertToAscii(b, outputFileName, width); }
public Add(Bitmap overlayImage) : base(overlayImage) { InitFormatTranslations(); }
} //FolderSelect_Click() private void btn_Process_Click(object sender, EventArgs e) { if (folderPath != "") { string saveFolderPath = ""; folderBrowserDialog_Save.ShowDialog(); saveFolderPath = folderBrowserDialog_Save.SelectedPath; if(saveFolderPath != "") { DateTime beforDT = DateTime.Now; fileMap = new Dictionary<string, string>(); copyList = new List<FileInfo>(); errorListMap = new Dictionary<string, string>(); getFile(folderPath, fileMap); int count = 0; try { foreach (KeyValuePair<string, string> kvp in fileMap) { if (File.Exists(kvp.Value)) { try { Bitmap rgbTexture = new Bitmap(kvp.Key); Bitmap alphaTexture = new Bitmap(kvp.Value); string saveName = kvp.Key.Replace(folderPath, ""); //To get the path with subfolder for each image string pattern = @"\\\S*\\"; if (!Directory.Exists(saveFolderPath + Regex.Match(saveName, pattern))) { Directory.CreateDirectory(saveFolderPath + Regex.Match(saveName, pattern)); } if(rgbTexture.Width == alphaTexture.Width && rgbTexture.Height == alphaTexture.Height) { Bitmap textureWithAlpha = new Bitmap(mergeImage(rgbTexture, alphaTexture)); textureWithAlpha.Save(saveFolderPath + saveName, ImageFormat.Png); count++; richTextBox_Console.AppendText("\n" + kvp.Key + " proceeded Remain file(s): " + (fileMap.Keys.Count - count - errorListMap.Count)); richTextBox_Console_Foucus(); textureWithAlpha.Dispose(); } else { errorListMap.Add(kvp.Key, kvp.Value); richTextBox_Console.AppendText("\n" + kvp.Key + " :" + " Resoluiton check failed please make sure Alpha texture sharing the same resolution as RGB's "); richTextBox_Console_Foucus(); } rgbTexture.Dispose(); alphaTexture.Dispose(); } catch (Exception ex) { Console.WriteLine(kvp.Key + " :" + ex.Message + " Please make sure Alpha texture sharing the same resolution as RGB's"); errorListMap.Add(kvp.Key,kvp.Value); richTextBox_Console.AppendText("\n" + kvp.Key + " :" + ex.Message); richTextBox_Console_Foucus(); } } else { errorListMap.Add(kvp.Key, kvp.Value); richTextBox_Console.AppendText("\n" + kvp.Value + " Skipped : Can not find Alpha texture for it."); richTextBox_Console_Foucus(); }//if end } //foreach end } catch (Exception ex) { Console.WriteLine("flag1: " + ex.Message); } finally { Console.WriteLine("Total files : " + fileMap.Keys.Count + " " + count + " file(s) are proceed , " + errorListMap.Count + " file(s) are skiped."); richTextBox_Console.AppendText("\nTotal files : " + fileMap.Keys.Count + " " + count + " file(s) were proceeded , " + errorListMap.Count + " file(s) are skipped. "); richTextBox_Console_Foucus(); } DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforDT); richTextBox_Console.AppendText("Time:" + ts.TotalSeconds + " s\n"); richTextBox_Console_Foucus(); if (copyList.Count > 0) { unmatchedFileProcessing(); } if(errorListMap.Count > 0) { errorFileProcessing(); } } //internal if end } else { MessageBox.Show("令人窒息的操作顺序 我不会怪你的....."); } //if end } //Process_Click()
/// <summary> /// /// </summary> /// <param name="cancelToken"></param> /// <param name="tileProvider"></param> /// <param name="tileInfo"></param> /// <param name="bitmaps"></param> /// <param name="retry"></param> /// <returns>true if thread finished without getting cancellation signal, false = cancelled</returns> private bool GetTileOnThread(CancellationToken cancelToken, ITileProvider tileProvider, TileInfo tileInfo, MemoryCache<Bitmap> bitmaps, bool retry) { byte[] bytes; try { if (cancelToken.IsCancellationRequested) cancelToken.ThrowIfCancellationRequested(); //We may have gotten the tile from another thread now.. if (bitmaps.Find(tileInfo.Index) != null) { return true; } if (Logger.IsDebugEnabled) Logger.DebugFormat("Calling gettile on provider for tile {0},{1},{2}", tileInfo.Index.Level, tileInfo.Index.Col, tileInfo.Index.Row); bytes = tileProvider.GetTile(tileInfo); if (cancelToken.IsCancellationRequested) cancelToken.ThrowIfCancellationRequested(); using (var ms = new MemoryStream(bytes)) { Bitmap bitmap = new Bitmap(ms); bitmaps.Add(tileInfo.Index, bitmap); if (_fileCache != null && !_fileCache.Exists(tileInfo.Index)) { AddImageToFileCache(tileInfo, bitmap); } if (cancelToken.IsCancellationRequested) cancelToken.ThrowIfCancellationRequested(); OnMapNewTileAvaliable(tileInfo, bitmap); } return true; } catch (WebException ex) { if (Logger.IsDebugEnabled) Logger.DebugFormat("Exception downloading tile {0},{1},{2} {3}", tileInfo.Index.Level, tileInfo.Index.Col, tileInfo.Index.Row, ex.Message); if (retry) { return GetTileOnThread(cancelToken, tileProvider, tileInfo, bitmaps, false); } else { if (_showErrorInTile) { //an issue with this method is that one an error tile is in the memory cache it will stay even //if the error is resolved. PDD. var bitmap = new Bitmap(_source.Schema.Width, _source.Schema.Height); using (var graphics = Graphics.FromImage(bitmap)) { graphics.DrawString(ex.Message, new Font(FontFamily.GenericSansSerif, 12), new SolidBrush(Color.Black), new RectangleF(0, 0, _source.Schema.Width, _source.Schema.Height)); } //Draw the Timeout Tile OnMapNewTileAvaliable(tileInfo, bitmap); //With timeout we don't add to the internal cache //bitmaps.Add(tileInfo.Index, bitmap); } return true; } } catch (System.OperationCanceledException tex) { if (Logger.IsInfoEnabled) { Logger.InfoFormat("TileAsyncLayer - Thread aborting: {0}", Thread.CurrentThread.Name); Logger.InfoFormat(tex.Message); } return false; } catch (Exception ex) { Logger.Warn("TileAsyncLayer - GetTileOnThread Exception", ex); //This is not due to cancellation so return true return true; } }
public UnsafeBitmap(Bitmap bitmap) { this.bitmap = new Bitmap(bitmap); }
/// <summary> /// Renders the layer /// </summary> /// <param name="graphics">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics graphics, Map map) { var bbox = map.Envelope; var extent = new Extent(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY); int level = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, map.PixelSize); var tiles = _source.Schema.GetTilesInView(extent, level); //Abort previous running Threads Cancel(); using (var ia = new ImageAttributes()) { if (!_transparentColor.IsEmpty) ia.SetColorKey(_transparentColor, _transparentColor); #if !PocketPC ia.SetWrapMode(WrapMode.TileFlipXY); #endif foreach (TileInfo info in tiles) { if (_bitmaps.Find(info.Index) != null) { //draws directly the bitmap var bb = new Envelope(new Coordinate(info.Extent.MinX, info.Extent.MinY), new Coordinate(info.Extent.MaxX, info.Extent.MaxY)); HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index), _source.Schema.Width, _source.Schema.Height, ia); } else if (_fileCache != null && _fileCache.Exists(info.Index)) { Bitmap img = GetImageFromFileCache(info) as Bitmap; _bitmaps.Add(info.Index, img); //draws directly the bitmap var btExtent = info.Extent; var bb = new Envelope(new Coordinate(btExtent.MinX, btExtent.MinY), new Coordinate(btExtent.MaxX, btExtent.MaxY)); HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index), _source.Schema.Width, _source.Schema.Height, ia); } else { var cancelToken = new CancellationTokenSource(); var token = cancelToken.Token; var l_info = info; if (Logger.IsDebugEnabled) Logger.DebugFormat("Starting new Task to download tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row); var t = new System.Threading.Tasks.Task(delegate { if (token.IsCancellationRequested) token.ThrowIfCancellationRequested(); if (Logger.IsDebugEnabled) Logger.DebugFormat("Task started for download of tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row); var res = GetTileOnThread(token, _source.Provider, l_info, _bitmaps, true); if (res) { Interlocked.Decrement(ref _numPendingDownloads); var e = DownloadProgressChanged; if (e != null) e(_numPendingDownloads); } }, token); var dt = new DownloadTask() { CancellationToken = cancelToken, Task = t }; lock (_currentTasks) { _currentTasks.Add(dt); _numPendingDownloads++; } t.Start(); } } } }
public Captcha(int width, int height) { bitmap = new Bitmap(width, height); random = new Random(); graphics = Graphics.FromImage(bitmap); }