private void button3_Click(object sender, EventArgs e) { if (listView1.SelectedItems.Count != 1) return; OpenFileDialog od = new OpenFileDialog(); od.Filter = "Bitmap file (*.bmp)|*.bmp"; od.FilterIndex = 0; if (od.ShowDialog() == DialogResult.OK) { Section s = listView1.SelectedItems[0].Tag as Section; try { Bitmap bmp = new Bitmap(od.FileName); s.import(bmp); bmp.Dispose(); pictureBox1.Image = s.image(); listView1.SelectedItems[0].SubItems[3].Text = s.cnt.ToString(); button4.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public GLTextureObject(Bitmap bitmap, int numMipMapLevels) { _id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, _id); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureBaseLevel, 0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, numMipMapLevels - 1); Size currentSize = new Size(bitmap.Width, bitmap.Height); Bitmap currentBitmap = new Bitmap(bitmap); for (int i = 0; i < numMipMapLevels; i++) { //Load currentBitmap BitmapData currentData = currentBitmap.LockBits(new System.Drawing.Rectangle(0, 0, currentBitmap.Width, currentBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, i, PixelInternalFormat.Rgba, currentSize.Width, currentSize.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, currentData.Scan0); currentBitmap.UnlockBits(currentData); //Prepare for next iteration currentSize = new Size(currentSize.Width / 2, currentSize.Height / 2); Bitmap tempBitmap = scaleBitmap(currentBitmap, currentSize); currentBitmap.Dispose(); currentBitmap = tempBitmap; } currentBitmap.Dispose(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.NearestMipmapLinear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); }
/// <summary> /// Validates input picture dimensions /// </summary> /// <param name="PictureBinary">PictureBinary</param> /// <returns></returns> public static byte[] ValidatePicture(byte[] PictureBinary) { using (MemoryStream stream = new MemoryStream(PictureBinary)) { Bitmap b = new Bitmap(stream); int maxSize = 1024; if ((b.Height > maxSize) || (b.Width > maxSize)) { Size newSize = CalculateDimensions(b.Size, maxSize); Bitmap newBitMap = new Bitmap(newSize.Width, newSize.Height); Graphics g = Graphics.FromImage(newBitMap); g.DrawImage(b, 0, 0, newSize.Width, newSize.Height); MemoryStream m = new MemoryStream(); newBitMap.Save(m, ImageFormat.Jpeg); newBitMap.Dispose(); b.Dispose(); return m.GetBuffer(); } else { b.Dispose(); return PictureBinary; } } }
/// <summary>Loads a texture from the specified file.</summary> /// <param name="file">The file that holds the texture.</param> /// <param name="texture">Receives the texture.</param> /// <returns>Whether loading the texture was successful.</returns> internal bool Parse(string file, out Texture texture) { /* * Read the bitmap. This will be a bitmap of just * any format, not necessarily the one that allows * us to extract the bitmap data easily. * */ System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(file); Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); /* * If the bitmap format is not already 32-bit BGRA, * then convert it to 32-bit BGRA. * */ if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { Bitmap compatibleBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(compatibleBitmap); graphics.DrawImage(bitmap, rect, rect, GraphicsUnit.Pixel); graphics.Dispose(); bitmap.Dispose(); bitmap = compatibleBitmap; } /* * Extract the raw bitmap data. * */ BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat); if (data.Stride == 4 * data.Width) { /* * Copy the data from the bitmap * to the array in BGRA format. * */ byte[] raw = new byte[data.Stride * data.Height]; System.Runtime.InteropServices.Marshal.Copy(data.Scan0, raw, 0, data.Stride * data.Height); bitmap.UnlockBits(data); int width = bitmap.Width; int height = bitmap.Height; bitmap.Dispose(); /* * Change the byte order from BGRA to RGBA. * */ for (int i = 0; i < raw.Length; i += 4) { byte temp = raw[i]; raw[i] = raw[i + 2]; raw[i + 2] = temp; } texture = new Texture(width, height, 32, raw); return true; } else { /* * The stride is invalid. This indicates that the * CLI either does not implement the conversion to * 32-bit BGRA correctly, or that the CLI has * applied additional padding that we do not * support. * */ bitmap.UnlockBits(data); bitmap.Dispose(); CurrentHost.ReportProblem(ProblemType.InvalidOperation, "Invalid stride encountered."); texture = null; return false; } }
protected void lbImgUpload_Click(object sender, EventArgs e) { if (txtBookName.Text != "" && imgUpload.HasFile) { string filepath = imgUpload.PostedFile.FileName; string pat = @"\\(?:.+)\\(.+)\.(.+)"; Regex r = new Regex(pat); Match m = r.Match(filepath); //string file_ext = m.Groups[2].Captures[0].ToString(); //string filename = m.Groups[1].Captures[0].ToString(); string file_ext = "jpg"; string file = txtBookName.Text + "." + file_ext; System.IO.FileInfo files = new System.IO.FileInfo(MapPath(file)); if (files.Exists) { files.Delete(); } int width = 145; int height = 165; using (System.Drawing.Bitmap img = DataManager.ResizeImage(new System.Drawing.Bitmap(imgUpload.PostedFile.InputStream), width, height, DataManager.ResizeOptions.ExactWidthAndHeight)) { img.Save(Server.MapPath("img/") + file); imgUpload.PostedFile.InputStream.Close(); ImageLogo = DataManager.ConvertImageToByteArray(img, System.Drawing.Imaging.ImageFormat.Tiff); img.Dispose(); } string strFilename = "img/" + file; imgLogo.ImageUrl = "~/tmpHandler.ashx?filename=" + strFilename + ""; } else { ClientScript.RegisterStartupScript(this.GetType(), "ale", "alert('Please input book name, and then browse an image!!');", true); } }
private void CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 25); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 30); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); System.Drawing.Font f = new System.Drawing.Font("Arial", 20, System.Drawing.FontStyle.Bold); System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White); //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(System.Drawing.Color.Blue); g.DrawString(checkCode, f, b, 3, 3); System.Drawing.Pen blackPen = new System.Drawing.Pen(System.Drawing.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(); }
public void VisualizeNeuralNetToFile(string neuralNetPicFilePath) { FastIncrementalLayoutSettings fastSettings = new FastIncrementalLayoutSettings { AvoidOverlaps = true, NodeSeparation = 30, RouteEdges = true }; SugiyamaLayoutSettings settings = new SugiyamaLayoutSettings { FallbackLayoutSettings = fastSettings }; m_opsViz.LayoutAlgorithmSettings = settings; Microsoft.Msagl.GraphViewerGdi.GraphRenderer renderer = new Microsoft.Msagl.GraphViewerGdi.GraphRenderer(m_opsViz); renderer.CalculateLayout(); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)m_opsViz.Width, (int)m_opsViz.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); renderer.Render(bitmap); bitmap.Save(neuralNetPicFilePath); bitmap.Dispose(); }
internal static string[] ConvertTiffToJpeg(string fileName) { using (Image imageFile = Image.FromFile(fileName)) { FrameDimension frameDimensions = new FrameDimension(imageFile.FrameDimensionsList[0]); int frameNum = imageFile.GetFrameCount(frameDimensions); string[] jpegPaths = new string[frameNum]; for (int frame = 0; frame < frameNum; frame++) { imageFile.SelectActiveFrame(frameDimensions, frame); using (Bitmap bmp = new Bitmap(imageFile)) { string tempFileName = Path.GetTempFileName(); FileInfo fileInfo = new FileInfo(tempFileName); fileInfo.Attributes = FileAttributes.Temporary; jpegPaths[frame] = tempFileName; bmp.Save(jpegPaths[frame], ImageFormat.Jpeg); bmp.Dispose(); } } return jpegPaths; } }
/// <summary> /// Captures a screenshot of the specified window at the specified /// bitmap size. <para/>NOTE: This method will not accurately capture controls /// that are hidden or obstructed (partially or completely) by another control (e.g. hidden tabs, /// or MDI child windows that are obstructed by other child windows/forms). /// </summary> /// <param name="windowHandle">The window handle.</param> /// <param name="bitmapSize">The requested bitmap size.</param> /// <returns>A screen capture of the window.</returns> public static Bitmap GrabWindowBitmap(IntPtr windowHandle, System.Drawing.Size bitmapSize) { if (bitmapSize.Height <= 0 || bitmapSize.Width <= 0) { return null; } IntPtr windowDC = IntPtr.Zero; try { windowDC = TabbedThumbnailNativeMethods.GetWindowDC(windowHandle); System.Drawing.Size realWindowSize; TabbedThumbnailNativeMethods.GetClientSize(windowHandle, out realWindowSize); if (realWindowSize == System.Drawing.Size.Empty) { realWindowSize = new System.Drawing.Size(200, 200); } System.Drawing.Size size = (bitmapSize == System.Drawing.Size.Empty) ? realWindowSize : bitmapSize; Bitmap targetBitmap = null; try { targetBitmap = new Bitmap(size.Width, size.Height); using (Graphics targetGr = Graphics.FromImage(targetBitmap)) { IntPtr targetDC = targetGr.GetHdc(); uint operation = 0x00CC0020 /*SRCCOPY*/; System.Drawing.Size ncArea = WindowUtilities.GetNonClientArea(windowHandle); bool success = TabbedThumbnailNativeMethods.StretchBlt( targetDC, 0, 0, targetBitmap.Width, targetBitmap.Height, windowDC, ncArea.Width, ncArea.Height, realWindowSize.Width, realWindowSize.Height, operation); targetGr.ReleaseHdc(targetDC); if (!success) { return null; } return targetBitmap; } } catch { if (targetBitmap != null) { targetBitmap.Dispose(); } throw; } } finally { if (windowDC != IntPtr.Zero) { TabbedThumbnailNativeMethods.ReleaseDC(windowHandle, windowDC); } } }
public void Dispose() { GC.SuppressFinalize(this); sdBuffer?.Dispose(); sdGraphics?.Dispose(); GC.Collect(); }
private void CreateCheckCodeImage(string checkCode) { checkCode = checkCode ?? string.Empty; if (!string.IsNullOrEmpty(checkCode)) { Bitmap image = new Bitmap(80, 15); Graphics graphics = Graphics.FromImage(image); try { Random random = new Random(); graphics.Clear(Color.White); Font font = new Font("Fixedsys", 12f, FontStyle.Bold); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(random.Next(0xff), random.Next(0xff), random.Next(0xff)), Color.FromArgb(random.Next(200), random.Next(200), random.Next(200)), 1.2f, true); graphics.DrawString(checkCode, font, brush, (float)-3f, (float)-2f); for (int i = 0; i < 80; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Gif); base.Response.ClearContent(); base.Response.ContentType = "image/Gif"; base.Response.BinaryWrite(stream.ToArray()); } finally { graphics.Dispose(); image.Dispose(); } } }
private static void InitializeBitmapAndGraphics(int width, int height) { _graphics?.Dispose(); _bitmap?.Dispose(); _bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); _graphics = Graphics.FromImage(_bitmap); }
public bool export() { checkStuff(); SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = LanguageManager.Get("Filters", "png"); if (ofd.ShowDialog(win) == DialogResult.Cancel) return false; calcSizes(); Bitmap b = new Bitmap(tx, ty); Graphics bgfx = Graphics.FromImage(b); int x = 0; foreach (PixelPalettedImage img in imgs) { int y = 0; foreach (Palette pal in pals) { Bitmap bb = img.render(pal); bgfx.DrawImage(bb, x, y, bb.Width, bb.Height); bb.Dispose(); y += tys; } x += img.getWidth(); } b.Save(ofd.FileName); b.Dispose(); return true; }
/// <summary> /// Creates a screenshot from a hidden window. /// </summary> /// <param name="windowHandle"> /// The handle of the window. /// </param> /// <returns> /// A <see cref="Bitmap"/> of the window. /// </returns> public static Bitmap CreateFromHidden(IntPtr windowHandle) { Bitmap bmpScreen = null; try { Rectangle r; using (Graphics windowGraphic = Graphics.FromHdc(new IntPtr(NativeWin32.GetWindowDC(windowHandle)))) { r = Rectangle.Round(windowGraphic.VisibleClipBounds); } bmpScreen = new Bitmap(r.Width, r.Height); using (Graphics g = Graphics.FromImage(bmpScreen)) { IntPtr hdc = g.GetHdc(); try { NativeWin32.PrintWindow(windowHandle, hdc, 0); } finally { g.ReleaseHdc(hdc); } } } catch { if (bmpScreen != null) { bmpScreen.Dispose(); } } return bmpScreen; }
private void MakeThumbImage(string sPath, string stPath, int nWidth, int nHeight) { System.Drawing.Image sImage = System.Drawing.Image.FromFile(sPath); int tw = nWidth; int th = nHeight; ///原始图片的宽度和高度 int sw = sImage.Width; int sh = sImage.Height; if (sw > tw) { sw = tw; } if (sh > th) { sh = th; } System.Drawing.Bitmap objPic, objNewPic; objPic = new System.Drawing.Bitmap(sPath); objNewPic = new System.Drawing.Bitmap(objPic, sw, sh); objNewPic.Save(stPath); sImage.Dispose(); objPic.Dispose(); objNewPic.Dispose(); }
private void InsertImage(string xh) { string cmdText = "select name,origitalbmp from studentinfotb where xh='" + xh + "'"; SqlConnection conn = new SqlConnection(sqlConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand(cmdText, conn); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { string name = dr[0].ToString(); byte[] photo = (byte[])dr[1]; dr.Close(); System.IO.MemoryStream ms = new System.IO.MemoryStream(photo); System.Drawing.Image image = System.Drawing.Image.FromStream(ms); System.Drawing.Bitmap bt = new System.Drawing.Bitmap(image, 390, 566); string imageName = Server.MapPath(@"~/temppics/" + xh + "origitalbmp.jpg"); bt.Save(imageName); bt.Dispose(); DrawImage(imageName, "10280" + xh, name, 155.0f, 340.0f); UploadImage(xh, imageName); } conn.Close(); }
public override void DrawEffectImage(Bitmap current, Bitmap next, EffectingPanel effecingPanel) { int step = 1; Graphics bg; Bitmap doubleBufferingBitmap; SolidBrush solidBrush; Rectangle rectangle; Matrix matrix = null; try { doubleBufferingBitmap = new Bitmap(current); // ダブルバッファリング用画面 bg = Graphics.FromImage(doubleBufferingBitmap); // ダブルバッファリング用画面描画用Graphics solidBrush = new SolidBrush(System.Drawing.Color.Black); rectangle = new Rectangle(0, 0, current.Width, current.Height); matrix = new Matrix(); step = doubleBufferingBitmap.Width / 50; if (step < 1) { step = 1; } ResetInterval(); for (int x = 0; x < doubleBufferingBitmap.Width; x += step) { bg.ResetTransform(); // リセット座標変換 bg.FillRectangle(solidBrush, rectangle); // current画像 matrix.Reset(); matrix.Translate(x, 0, MatrixOrder.Append); // 原点移動 bg.Transform = matrix; // 座標設定 bg.DrawImage(current, 0, 0); // next画像 matrix.Reset(); matrix.Translate(x - doubleBufferingBitmap.Width, 0, MatrixOrder.Append); bg.Transform = matrix; bg.DrawImage(next, 0, 0); effecingPanel.pictureBox.Image = doubleBufferingBitmap; effecingPanel.pictureBox.Refresh(); DoEventAtIntervals(); } matrix.Dispose(); bg.Dispose(); doubleBufferingBitmap.Dispose(); effecingPanel.pictureBox.Image = next; } catch (SystemException ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Creates an action result containing the file contents of a png/image with the captcha chars /// </summary> public static ActionResult CaptchaResult(SessionWrapper session) { var randomText = GenerateRandomText(6); var hash = Utils.GetMd5Hash(randomText + GetSalt(), Encoding.ASCII); session.CaptchaHash = hash; var rnd = new Random(); var fonts = new[] { "Verdana", "Times New Roman" }; float orientationAngle = rnd.Next(0, 359); const int height = 30; const int width = 120; var index0 = rnd.Next(0, fonts.Length); var familyName = fonts[index0]; using (var bmpOut = new Bitmap(width, height)) { var g = Graphics.FromImage(bmpOut); var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height), Color.White, Color.DarkGray, orientationAngle); g.FillRectangle(gradientBrush, 0, 0, width, height); DrawRandomLines(ref g, width, height); g.DrawString(randomText, new Font(familyName, 18), new SolidBrush(Color.Gray), 0, 2); var ms = new MemoryStream(); bmpOut.Save(ms, ImageFormat.Png); var bmpBytes = ms.GetBuffer(); bmpOut.Dispose(); ms.Close(); return new FileContentResult(bmpBytes, "image/png"); } }
public void Draw() { //save current set of images using (Bitmap bmp = new Bitmap(main_panel.Width, main_panel.Height)) { main_panel.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, main_panel.Width, main_panel.Height)); bmp.Save("empty" + h_counter.ToString() + ".jpeg", ImageFormat.Jpeg); bmp.Dispose(); } //open this set var image = System.Drawing.Image.FromFile("empty" + h_counter.ToString() + ".jpeg"); Graphics g = Graphics.FromImage(image); Color colorr = Color.FromArgb(255, 255, 0, 0); g.DrawCurve(new Pen(new SolidBrush(colorr), 50), list.ToArray()); //draw points on this set of images //foreach (var item in list) //{ // //менять оттенок цвета для набора точек // Color color = Color.FromArgb(255, 255, 0, 0); // g.FillRectangle(new SolidBrush(color), item.X, item.Y, 5, 5); //} //save this set image.Save("result" + h_counter.ToString() + ".jpeg"); list.Clear(); }
public static void GenerateThumbImg(string originImg, int width, int height, string desUrl) { Bitmap originalBmp = null; var originImage = Image.FromFile(HttpContext.Current.Server.MapPath("~/Upload/SliderImg" + originImg)); originalBmp = new Bitmap(originImage); // 源图像在新图像中的位置 int left, top; if (originalBmp.Width <= width && originalBmp.Height <= height) { // 原图像的宽度和高度都小于生成的图片大小 left = (int)Math.Round((decimal)(width - originalBmp.Width) / 2); top = (int)Math.Round((decimal)(height - originalBmp.Height) / 2); // 最终生成的图像 Bitmap bmpOut = new Bitmap(width, height); using (Graphics graphics = Graphics.FromImage(bmpOut)) { // 设置高质量插值法 graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; // 清空画布并以白色背景色填充 graphics.Clear(Color.White); //加上边框 //Pen pen = new Pen(ColorTranslator.FromHtml("#cccccc")); // graphics.DrawRectangle(pen, 0, 0, width - 1, height - 1); // 把源图画到新的画布上 graphics.DrawImage(originalBmp, left, top); } //保存为文件,tpath 为要保存的路径 bmpOut.Dispose(); return; } }
/// <summary> /// From a path, return a byte[] of the image. /// </summary> /// <param name="uriPath"> /// External image path. /// </param> /// <param name="length"> /// The image size in bytes. /// </param> /// <returns> /// The get image parameters. /// </returns> public static string GetImageParameters(Uri uriPath, out long length) { string pseudoMime = string.Empty; string contentType = string.Empty; using (Stream stream = GetRemoteData(uriPath, out length, out contentType)) { Bitmap img = null; try { img = new Bitmap(stream); // no need to set here mime exatly this is reserved for customization. pseudoMime = "{0}!{1};{2}".FormatWith(contentType, img.Width, img.Height); } catch { return string.Empty; } finally { if (img != null) { img.Dispose(); } } stream.Close(); } return pseudoMime; }
private void CreateImage(string checkCode) { int width = checkCode.Length * 14; Bitmap image = new Bitmap(width, 20); Graphics graphics = Graphics.FromImage(image); Font font = new Font("Arial ", 10f); Brush brush = new SolidBrush(Color.Black); Brush brush2 = new SolidBrush(Color.FromArgb(0xa6, 8, 8)); graphics.Clear(ColorTranslator.FromHtml("#99C1CB")); char[] chArray = checkCode.ToCharArray(); for (int i = 0; i < chArray.Length; i++) { if ((chArray[i] >= '0') && (chArray[i] <= '9')) { graphics.DrawString(chArray[i].ToString(), font, brush2, (float) (3 + (i * 12)), 3f); } else { graphics.DrawString(chArray[i].ToString(), font, brush, (float) (3 + (i * 12)), 3f); } } MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); base.Response.Cache.SetNoStore(); base.Response.ClearContent(); base.Response.ContentType = "image/Jpeg"; base.Response.BinaryWrite(stream.ToArray()); graphics.Dispose(); image.Dispose(); }
public Bitmap DecodeFromPointer(IntPtr data, long length) { int w = 0, h = 0; //Validate header and determine size if (NativeMethods.WebPGetInfo(data, (UIntPtr)length, ref w, ref h) == 0) throw new Exception("Invalid WebP header detected"); bool success = false; Bitmap b = null; BitmapData bd = null; try { //Allocate canvas b = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Lock surface for writing bd = b.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Decode to surface IntPtr result = NativeMethods.WebPDecodeBGRAInto(data, (UIntPtr)length, bd.Scan0, (UIntPtr)( bd.Stride * bd.Height), bd.Stride); if (bd.Scan0 != result) throw new Exception("Failed to decode WebP image with error " + (long)result); success = true; } finally { //Unlock surface if (bd != null && b != null) b.UnlockBits(bd); //Dispose of bitmap if anything went wrong if (!success && b != null) b.Dispose(); } return b; }
public void ProcessEMF(byte[] emf) { try { _ms = new MemoryStream(emf); _mf = new Metafile(_ms); _bm = new Bitmap(1, 1); g = Graphics.FromImage(_bm); //XScale = Width / _mf.Width; //YScale = Height/ _mf.Height; m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback); g.EnumerateMetafile(_mf, new Point(0, 0), m_delegate); } finally { if (g != null) g.Dispose(); if (_bm != null) _bm.Dispose(); if (_ms != null) { _ms.Close(); _ms.Dispose(); } } }
public byte[] GetCaptchaImage(string checkCode) { Bitmap image = new Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 15))), 25); Graphics g = Graphics.FromImage(image); try { Random random = new Random(); g.Clear(Color.AliceBlue); Font font = new Font("Comic Sans MS", 14, FontStyle.Bold); string str = ""; System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); for (int i = 0; i < checkCode.Length; i++) { str = str + checkCode.Substring(i, 1); } g.DrawString(str, font, new SolidBrush(Color.Blue), 0, 0); g.Flush(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } finally { g.Dispose(); image.Dispose(); } }
internal static Image DrawText(string text, Font font, Color textColor, Color backColor) { //first, create a dummy bitmap just to get a graphics object Image img = new Bitmap(1, 1); Graphics drawing = Graphics.FromImage(img); //measure the string to see how big the image needs to be SizeF textSize = drawing.MeasureString(text, font); //free up the dummy image and old graphics object img.Dispose(); drawing.Dispose(); //create a new image of the right size img = new Bitmap((int)textSize.Width - Convert.ToInt32(font.Size * 1.5), (int)textSize.Height, PixelFormat.Format24bppRgb); drawing = Graphics.FromImage(img); //paint the background drawing.Clear(backColor); //create a brush for the text Brush textBrush = new SolidBrush(textColor); drawing.DrawString(text, font, textBrush, 0, 0); drawing.Save(); textBrush.Dispose(); drawing.Dispose(); return img; }
private void Form1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false); int fileCount = files.Count(); if( fileCount > 6 ) { fileCount = 6; } Bitmap henseiBitmap = new Bitmap(488 * 2, 376 * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Graphics henseiGraphics = Graphics.FromImage(henseiBitmap); List<String> fl = LoadFilePath(files); fl.Sort(); for (int i = 0; i < fileCount; i++) { Console.WriteLine(fl[i]); Bitmap orig = new Bitmap(fl[i].ToString()); Bitmap copy = orig.Clone(new Rectangle(312, 94, 488, 376), orig.PixelFormat); henseiGraphics.DrawImage(copy, henseiPosition[i, 0], henseiPosition[i, 1], copy.Width, copy.Height); orig.Dispose(); } henseiGraphics.Dispose(); String outPath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "hensei.png"); henseiBitmap.Save(outPath); System.Diagnostics.Process p = System.Diagnostics.Process.Start(outPath); }
/// <summary> /// 创建图片 /// </summary> /// <param name="checkCode"></param> private void CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 11); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 19); Graphics g = Graphics.FromImage(image); g.Clear(Color.White); //定义颜色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple }; Random rand = new Random(); //输出不同字体和颜色的验证码字符 for (int i = 0; i < checkCode.Length; i++) { int cindex = rand.Next(7); Font f = new System.Drawing.Font("Microsoft Sans Serif", 11); Brush b = new System.Drawing.SolidBrush(c[cindex]); g.DrawString(checkCode.Substring(i, 1), f, b, (i * 10) + 1, 0, StringFormat.GenericDefault); } //画一个边框 g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1); //输出到浏览器 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(); }
private void DrawInitBitmap() { Bitmap house = new Bitmap("house.bmp"); Bitmap car = new Bitmap("car.jpg"); Bitmap man = new Bitmap("man.gif"); Bitmap table = new Bitmap("table.bmp"); // 실제 출력할 이미지 m_bmpBackground = new Bitmap(500, 400); Font font = new Font("궁서체", 15); // 메모리 내부에서 이미지에 그리는 작업을 수행 Graphics g = Graphics.FromImage(m_bmpBackground); g.FillRectangle(Brushes.White, new Rectangle(0, 0, 500, 400)); g.DrawImage(house, new Rectangle(0,0,500,300)); // 궁전 g.FillEllipse(Brushes.Red, new Rectangle(330, 40, 30, 30)); g.DrawEllipse(Pens.Blue, new Rectangle(320, 30, 50, 50)); g.DrawImage(car, 50, 310); // 자동차 추가 g.DrawImage(man, 30, 310); // 사람 추가 g.DrawImage(table, 150, 300); // 식탁 추가 g.DrawString("더블 버퍼링 예제", font, Brushes.Black, 300, 320); g.Dispose(); // Bitmap 파일로 저장 font.Dispose(); car.Dispose(); man.Dispose(); table.Dispose(); }
/// <summary> /// Processes the image. /// </summary> /// <param name="factory">The current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class containing /// the image to process.</param> /// <returns> /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class. /// </returns> public Image ProcessImage(ImageFactory factory) { Bitmap newImage = null; Bitmap image = (Bitmap)factory.Image; try { newImage = new Bitmap(image); GaussianLayer gaussianLayer = this.DynamicParameter; Convolution convolution = new Convolution(gaussianLayer.Sigma) { Threshold = gaussianLayer.Threshold }; double[,] kernel = convolution.CreateGuassianSharpenFilter(gaussianLayer.Size); newImage = convolution.ProcessKernel(newImage, kernel); image.Dispose(); image = newImage; } catch (Exception ex) { if (newImage != null) { newImage.Dispose(); } throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); } return image; }
public static void ResizeImage(string fileName, int newWidth) { var fi = new FileInfo(fileName); if(!fi.Exists) throw new ArgumentException(fileName + " does not exist."); Bitmap newbmp; using (Bitmap originalBitmap = Bitmap.FromFile(fileName, true) as Bitmap) { float ratio = (float)newWidth / (float)originalBitmap.Width; double newHeight = (ratio) * originalBitmap.Height; newbmp = new Bitmap(newWidth, (int)newHeight); using (Graphics newg = Graphics.FromImage(newbmp)) { newg.DrawImage(originalBitmap, 0, 0, (float)newWidth, (float)newHeight); newg.Save(); } } newbmp.Save(fileName, ImageFormat.Jpeg); newbmp.Dispose(); }
/// <summary> /// Most of the time it just returns a black screen, this is because the game is rendering straight to the /// graphics card using directx and bypassing whatever windows usually uses for PrintWindow /// AFAIK directx screenshots only work if the window is currently visible (not overlaid by the bot itself) /// </summary> /// <returns></returns> public Image<Bgr, byte> TakeScreenshot() { Bitmap frame = new Bitmap(1024, 768); using (Graphics g = Graphics.FromImage(frame)) { IntPtr deviceContextHandle = g.GetHdc(); PrintWindow(GetGameWindowHandle(), deviceContextHandle, 1); g.ReleaseHdc(); } //we have the bitmap now //turn it into an Image for emgu BitmapData bmpData = frame.LockBits(new Rectangle(0, 0, frame.Width, frame.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); Image<Bgr, byte> tempImage = new Image<Bgr, byte>(frame.Width, frame.Height, bmpData.Stride, bmpData.Scan0); //to prevent any corrupted memory errors that crop up for some reason Image<Bgr, byte> image = tempImage.Clone(); frame.UnlockBits(bmpData); //dispose all unused image data to prevent memory leaks frame.Dispose(); tempImage.Dispose(); image.Save("screenshot.png"); return image; }
public static MemoryStream CompressImage(ImageFormat format, Stream stream, Size size, bool isbig) { using (var image = Image.FromStream(stream)) { Image bitmap = new Bitmap(size.Width, size.Height); Graphics g = Graphics.FromImage(bitmap); g.InterpolationMode = InterpolationMode.High; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(Color.Transparent); //按指定面积缩小 if (!isbig) { g.DrawImage(image, new Rectangle(0, 0, size.Width, size.Height), ImageCutSize(image, size), GraphicsUnit.Pixel); } //按等比例缩小 else { g.DrawImage(image, new Rectangle(0, 0, size.Width, size.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel); } var compressedImageStream = new MemoryStream(); bitmap.Save(compressedImageStream, format); g.Dispose(); bitmap.Dispose(); return compressedImageStream; } }
private void paintPreviewPicture() { if(gridMain.GetSelectedIndex()==-1) { return; } string imagePath=ImageNamesList[gridMain.GetSelectedIndex()]; Image tmpImg=new Bitmap(imagePath);//Could throw an exception if someone manually deletes the image right after this window loads. float imgScale=1;//will be between 0 and 1 if(tmpImg.PhysicalDimension.Height>picturePreview.Height || tmpImg.PhysicalDimension.Width>picturePreview.Width) {//image is too large //Image is larger than PictureBox, resize to fit. if(tmpImg.PhysicalDimension.Width/picturePreview.Width>tmpImg.PhysicalDimension.Height/picturePreview.Height) {//resize image based on width imgScale=picturePreview.Width/tmpImg.PhysicalDimension.Width; } else {//resize image based on height imgScale=picturePreview.Height/tmpImg.PhysicalDimension.Height; } } if(picturePreview.Image!=null) { picturePreview.Image.Dispose(); picturePreview.Image=null; } picturePreview.Image=new Bitmap(tmpImg,(int)(tmpImg.PhysicalDimension.Width*imgScale),(int)(tmpImg.PhysicalDimension.Height*imgScale)); labelImageSize.Text=Lan.g(this,"Image Size")+": "+(int)tmpImg.PhysicalDimension.Width+" x "+(int)tmpImg.PhysicalDimension.Height; picturePreview.Invalidate(); if(tmpImg!=null) { tmpImg.Dispose(); } tmpImg=null; }
public static Texture2D TextureFromBitmap(Bitmap image) { BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat); int bytes = data.Stride*image.Height; DataStream stream = new DataStream(bytes, true, true); stream.WriteRange(data.Scan0, bytes); stream.Position = 0; DataRectangle dRect = new DataRectangle(data.Stride, stream); Texture2DDescription texDesc = new Texture2DDescription { ArraySize = 1, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Format = Format.B8G8R8A8_UNorm, CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource, Usage = ResourceUsage.Immutable, Height = image.Height, Width = image.Width }; image.UnlockBits(data); image.Dispose(); Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect); stream.Dispose(); return texture; }
public static string md5Hash(this Bitmap bitmap) { try { if (bitmap.isNull()) return null; //based on code snippets from http://dotnet.itags.org/dotnet-c-sharp/85838/ using (var strm = new MemoryStream()) { var image = new Bitmap(bitmap); bitmap.Save(strm, System.Drawing.Imaging.ImageFormat.Bmp); strm.Seek(0, 0); byte[] bytes = strm.ToArray(); var md5 = new MD5CryptoServiceProvider(); byte[] hashed = md5.TransformFinalBlock(bytes, 0, bytes.Length); string hash = BitConverter.ToString(hashed).ToLower(); md5.Clear(); image.Dispose(); return hash; } } catch (Exception ex) { ex.log("in bitmap.md5Hash"); return ""; } }
public static Image ResizeFile(HttpPostedFileBase file, int targeWidth, int targetHeight) { Image originalImage = Image.FromStream(file.InputStream, true, true); var newImage = new MemoryStream(); Rectangle origRect = new Rectangle(0, 0, originalImage.Width, originalImage.Height); int newWidth = targeWidth; int newHeight = targetHeight; var bitmap = new Bitmap(newWidth, newHeight); try { using (Graphics g = Graphics.FromImage(bitmap)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(originalImage, new Rectangle(0, 0, newWidth, newHeight), origRect, GraphicsUnit.Pixel); bitmap.Save(newImage, originalImage.RawFormat); } return (Image)bitmap; } catch { if (bitmap != null) bitmap.Dispose(); throw new Exception("Error resizing file."); } }
public static void SaveToJpgFile(System.Drawing.Image img, string fileName) { if (!File.Exists(fileName)) { System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img, img.Width, img.Height); bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Dispose(); img.Dispose(); } }
private void AssignBMP(System.Drawing.Bitmap bmp) { lock (this) { mBitmap?.Dispose(); mBitmap = bmp; } Invalidate(); }
/// <summary> /// Images the resize. /// </summary> /// <param name="imageUrl">The image URL.</param> /// <param name="MaxWidth">Width of the max.</param> /// <param name="MaxHeight">Height of the max.</param> /// <returns></returns> string ImageResize(string imageUrl, int MaxWidth, int MaxHeight) { string imagePath = MapPath(imageUrl); System.Drawing.Bitmap img = new System.Drawing.Bitmap(imagePath); if (img.Width > MaxWidth || img.Height > MaxHeight) { double widthRatio = (double)img.Width / (double)MaxWidth; double heightRatio = (double)img.Height / (double)MaxHeight; double ratio = Math.Max(widthRatio, heightRatio); int newWidth = (int)(img.Width / ratio); int newHeight = (int)(img.Height / ratio); img.Dispose(); return(" width='" + newWidth.ToString() + "px'" + " height='" + newHeight.ToString() + "px' "); } else { img.Dispose(); return(""); } }
public void makeThumbnail(string it, string Imageurl) { if (File.Exists(Server.MapPath("~/images/" + it + ".jpg"))) { return; } else { try { System.Net.WebRequest request = System.Net.WebRequest.Create(Imageurl); request.Timeout = 10000; System.Net.HttpWebResponse httpresponse = (System.Net.HttpWebResponse)request.GetResponse(); Stream s = httpresponse.GetResponseStream(); System.Drawing.Image img = System.Drawing.Image.FromStream(s); int towidth = 135; int toheight = 80; int x = 0; int y = 0; int ow = img.Width; int oh = img.Height; System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.Drawing.Color.Transparent); g.DrawImage(img, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(Server.MapPath("~/images/" + it + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { img.Dispose(); bitmap.Dispose(); g.Dispose(); } return; } catch { return; } } }
protected void Page_Load(object sender, EventArgs e) { int Width = 0; int Height = 0; double centerX = 0; double centerY = 0; double Zoom = 0; string[] Layer; //Parse request parameters if (!int.TryParse(Request.Params["WIDTH"], out Width)) { throw(new ArgumentException("Invalid parameter")); } if (!int.TryParse(Request.Params["HEIGHT"], out Height)) { throw (new ArgumentException("Invalid parameter")); } if (!double.TryParse(Request.Params["ZOOM"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out Zoom)) { throw (new ArgumentException("Invalid parameter")); } if (!double.TryParse(Request.Params["X"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out centerX)) { throw (new ArgumentException("Invalid parameter")); } if (!double.TryParse(Request.Params["Y"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out centerY)) { throw (new ArgumentException("Invalid parameter")); } //Params OK SharpMap.Map map = InitializeMap(new System.Drawing.Size(Width, Height)); map.Center = new GeoAPI.Geometries.Coordinate(centerX, centerY); map.Zoom = Zoom; //Generate map System.Drawing.Bitmap img = (System.Drawing.Bitmap)map.GetMap(); //Stream the image to the client Response.ContentType = "image/png"; System.IO.MemoryStream MS = new System.IO.MemoryStream(); img.Save(MS, System.Drawing.Imaging.ImageFormat.Png); // tidy up img.Dispose(); byte[] buffer = MS.ToArray(); Response.OutputStream.Write(buffer, 0, buffer.Length); }
public static System.Drawing.Bitmap CombineBitmap(List <Bitmap> images, System.Drawing.Color backgroundColour) { System.Drawing.Bitmap finalImage = null; try { int width = 0; int height = 0; foreach (var bitmap in images) { //update the size of the final bitmap width += bitmap.Width; height = bitmap.Height > height ? bitmap.Height : height; } //create a bitmap to hold the combined image finalImage = new System.Drawing.Bitmap(width, height); //get a graphics object from the image so we can draw on it using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage)) { //set background color g.Clear(backgroundColour); //go through each image and draw it on the final image int offset = 0; foreach (System.Drawing.Bitmap image in images) { g.DrawImage(image, new System.Drawing.Rectangle(offset, 0, image.Width, image.Height)); offset += image.Width; } } return(finalImage); } catch (Exception) { finalImage?.Dispose(); throw; } //finally //{ // //clean up memory // foreach (System.Drawing.Bitmap image in images) // { // image.Dispose(); // } //} }
protected void Page_Load(object sender, EventArgs e) { VryImgGen gen = new VryImgGen(); string verifyCode = gen.CreateVerifyCode(5, 0); Session["VerifyCode"] = verifyCode.ToUpper(); System.Drawing.Bitmap bitmap = gen.CreateImage(verifyCode); System.IO.MemoryStream ms = new System.IO.MemoryStream();//5+1%a+s+p+x bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.Clear(); Response.ContentType = "image/Png"; Response.BinaryWrite(ms.GetBuffer()); bitmap.Dispose(); ms.Dispose(); ms.Close(); Response.End(); }
//Red Segmentation public static BitmapSource Procred(BitmapSource Image) { //Checks to see if there is an image if (Image != null) { //Converts to image<> MemoryStream Stream = new MemoryStream(); BitmapEncoder encoded = new BmpBitmapEncoder(); encoded.Frames.Add(BitmapFrame.Create(Image)); encoded.Save(Stream); System.Drawing.Bitmap myBmp = new System.Drawing.Bitmap(Stream); //Casts image to bitmap Image <Hsv, Byte> processed = new Image <Hsv, Byte>(myBmp); //Casts bitmap to image<Hsv, byte> //Main processing CvInvoke.Flip(processed, processed, Emgu.CV.CvEnum.FlipType.Horizontal); //Flips the image in the horizontal Image <Gray, Byte> Thr1, Thr2; //Creates two Grayscale images that will be used when segmenting Thr1 = processed.InRange(new Hsv(0, 120, 70), new Hsv(10, 255, 255)); //Handles first range for RED Thr2 = processed.InRange(new Hsv(170, 120, 70), new Hsv(180, 255, 255)); //Handles second range for RED Thr1 = Thr1 + Thr2; //Handles noise and cleans image Mat kernel = Mat.Ones(3, 3, Emgu.CV.CvEnum.DepthType.Cv32F, 1); //Creates 3x3 kernel for use as kernel CvInvoke.MorphologyEx(Thr1, Thr1, Emgu.CV.CvEnum.MorphOp.Open, kernel, new System.Drawing.Point(0, 0), 1, Emgu.CV.CvEnum.BorderType.Default, new MCvScalar(1)); CvInvoke.MorphologyEx(Thr1, Thr1, Emgu.CV.CvEnum.MorphOp.Dilate, kernel, new System.Drawing.Point(0, 0), 1, Emgu.CV.CvEnum.BorderType.Default, new MCvScalar(1)); //Extracts only RED parts from orignal image Mat Mask; //Creates Mat for converting mask to Mat Mask = Thr1.Mat; //Casts mask to Mat Image <Hsv, byte> Final = new Image <Hsv, byte>(processed.Width, processed.Height); //Creates Image<Hsv,byte> for final processed image CvInvoke.BitwiseAnd(processed, processed, Final, Mask); //ANDS mask with orignal image to retain only portions that are RED //Cleanup Mask.Dispose(); Thr1.Dispose(); Thr2.Dispose(); Stream.Dispose(); myBmp.Dispose(); return(BitmapSourceConvert.ToBitmapSource(Final)); //Returns processed image } else { return(null); } }
protected virtual void Dispose(bool disposing) { if (Disposed) { return; } if (disposing) { _Image?.Dispose(); _Image = null; _ThumbnailImage?.Dispose(); _ThumbnailImage = null; } _Disposed = true; }
public static void ResizeFromStream(string fromFile, string toFile) { int intNewWidth = 150; int intNewHeight = 180; System.Drawing.Image imgInput = System.Drawing.Image.FromFile(fromFile); //Determine image format System.Drawing.Imaging.ImageFormat fmtImageFormat = imgInput.RawFormat; //create new bitmap System.Drawing.Bitmap bmpResized = new System.Drawing.Bitmap(imgInput, intNewWidth, intNewHeight); //save bitmap to disk bmpResized.Save(toFile, fmtImageFormat); //release used resources imgInput.Dispose(); bmpResized.Dispose(); }
//另存图片,并修改大小。 public static void SaveImage(string fromFile, string toFile, double newWidth, double newHeight) { try { System.Drawing.Image myimage = System.Drawing.Image.FromStream(new MemoryStream(File.ReadAllBytes(fromFile))); double oldWidth = myimage.Width; double oldHeight = myimage.Height; if (oldWidth > newWidth || oldHeight > newHeight) { if (myimage.Width >= myimage.Height) { oldHeight = newHeight; oldWidth = newHeight / myimage.Height * myimage.Width; } else { oldWidth = newWidth; oldHeight = newWidth / myimage.Width * myimage.Height; } } System.Drawing.Size mysize = new System.Drawing.Size((int)oldWidth, (int)oldHeight); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(mysize.Width, mysize.Height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.Drawing.Color.Transparent); g.DrawImage(myimage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, myimage.Width, myimage.Height), System.Drawing.GraphicsUnit.Pixel); bitmap.Save(toFile, System.Drawing.Imaging.ImageFormat.Jpeg); g.Dispose(); bitmap.Dispose(); myimage.Dispose(); } catch { } }
protected void Page_Load(object sender, EventArgs e) { string codeType = Request["code"]; if (string.IsNullOrEmpty(codeType as string)) { codeType = "123"; } ValidateCodeImg vCodeImg = new ValidateCodeImg(); string verifyCode = vCodeImg.CreateVerifyCode(codeType, 6, 0); Session["ImgCode"] = verifyCode; System.Drawing.Bitmap bitmap = vCodeImg.CreateImage(verifyCode, false); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.Clear(); Response.ContentType = "image/Png"; Response.BinaryWrite(ms.GetBuffer()); bitmap.Dispose(); ms.Dispose(); ms.Close(); Response.End(); }
public void AutoImage(string strCompanyName) { Int16 swidth = Convert.ToInt16(strCompanyName.Length * 13); System.Drawing.Bitmap objBMP = new System.Drawing.Bitmap(swidth, 30); System.Drawing.Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP); objGraphics.Clear(System.Drawing.Color.White); objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; //' Configure font to use for text System.Drawing.Font objFont = new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Bold); string randomStr = strCompanyName; int[] myIntArray = new int[6]; int x; //That is to create the random # and add it to our string //Random autoRand = new Random(); //for (x = 0; x < 6; x++) //{ // myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9)); // randomStr += (myIntArray[x].ToString()); //} //This is to add the string to session cookie, to be compared later //' Write out the text objGraphics.DrawString(strCompanyName, objFont, System.Drawing.Brushes.Black, 3, 3); //' Set the content type and return the image //Response.ContentType = "image/GIF"; File.Delete(HttpContext.Current.Server.MapPath("~\\provider\\LogoImages\\Default.jpg")); objBMP.Save(HttpContext.Current.Server.MapPath("~\\provider\\LogoImages\\Default.jpg"), objBMP.RawFormat); objFont.Dispose(); objGraphics.Dispose(); objBMP.Dispose(); }
//Red Segmentation public static BitmapSource Procred(BitmapSource Image) { //Checks to see if there is an image if (Image != null) { //Converts to image<> MemoryStream Stream = new MemoryStream(); BitmapEncoder encoded = new BmpBitmapEncoder(); encoded.Frames.Add(BitmapFrame.Create(Image)); encoded.Save(Stream); System.Drawing.Bitmap myBmp = new System.Drawing.Bitmap(Stream); //Casts image to bitmap Image <Hsv, Byte> processed = new Image <Hsv, Byte>(myBmp); //Casts bitmap to image<Hsv, byte> //Main processing CvInvoke.Flip(processed, processed, Emgu.CV.CvEnum.FlipType.Horizontal); //Flips the image in the horizontal Image <Gray, Byte> Thr1; //Creates two Grayscale images that will be used when segmenting Thr1 = processed.InRange(new Hsv(170, 120, 70), new Hsv(180, 255, 255)); //Handles second range for RED //Handles noise and cleans image Mat kernel = Mat.Ones(3, 3, Emgu.CV.CvEnum.DepthType.Cv32F, 1); //Creates 3x3 kernel for use as kernel CvInvoke.MorphologyEx(Thr1, Thr1, Emgu.CV.CvEnum.MorphOp.Open, kernel, new System.Drawing.Point(0, 0), 1, Emgu.CV.CvEnum.BorderType.Default, new MCvScalar(1)); CvInvoke.MorphologyEx(Thr1, Thr1, Emgu.CV.CvEnum.MorphOp.Dilate, kernel, new System.Drawing.Point(0, 0), 1, Emgu.CV.CvEnum.BorderType.Default, new MCvScalar(1)); //Extracts only RED parts from orignal image Mat Mask; //Creates Mat for converting mask to Mat Mask = Thr1.Mat; //Casts mask to Mat Image <Hsv, byte> Redisolated = new Image <Hsv, byte>(processed.Width, processed.Height); //Creates Image<Hsv,byte> for final processed image //CvInvoke.BitwiseAnd(processed, processed, Redisolated, Mask); //ANDS mask with orignal image to retain only portions that are RED //Extracts biggest blob //Variables double Largestarea = 0; int Largestcontourindex = 0, X, Y; MCvPoint2D64f Center; Image <Gray, Byte> Centroid = new Image <Gray, Byte>(processed.Width, processed.Height); Image <Gray, Byte> Contourdrawn = new Image <Gray, Byte>(processed.Width, processed.Height); VectorOfVectorOfPoint Contours = new VectorOfVectorOfPoint(); Mat Hierarchy = new Mat(); //Processing CvInvoke.FindContours(Thr1, Contours, Hierarchy, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple); //Finds contours in image //Iterates through each contour for (int i = 0; i < Contours.Size; i++) { double a = CvInvoke.ContourArea(Contours[i], false); // Find the area of contour if (a > Largestarea) { Largestarea = a; Largestcontourindex = i; //Stores the index of largest contour //bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour } } CvInvoke.DrawContours(Contourdrawn, Contours, Largestcontourindex, new MCvScalar(255, 255, 255), 10, Emgu.CV.CvEnum.LineType.Filled, Hierarchy, 0); //Draws biggest contour on blank image Moments moments = CvInvoke.Moments(Contourdrawn, true); //Gets the moments of the dranw contour Center = moments.GravityCenter; //converts the moment to a center try { X = Convert.ToInt32(Center.X); //Converts to integer Y = Convert.ToInt32(Center.Y); Debug.WriteLine("X - {0}, Y - {1}", X, Y); //Prints centre co-ords to console CvInvoke.Circle(Centroid, new System.Drawing.Point(X, Y), 10, new MCvScalar(255, 255, 255), -1); } catch { Debug.WriteLine("No RED in detected"); } //Cleanup Mask.Dispose(); Thr1.Dispose(); Stream.Dispose(); myBmp.Dispose(); return(BitmapSourceConvert.ToBitmapSource(Centroid)); //Returns processed image } else { return(null); } }
private void CreateCheckCodeImage(string checkCode) { if (checkCode == null || checkCode.Trim() == String.Empty) { return; } System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(System.Drawing.Color.White); //画图片的背景噪音线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2); } System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true); int cySpace = 16; for (int i = 0; i < validateCodeCount; i++) { g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1); } //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } }
public ArrayList batUpload() { //string shopName = ""; //string strSQL = "select shopName from T_Shop_User where shopid=(select ProviderInfo from T_Goods_info where goodsid='" + goodsId + "' and Datafrom='ShopSeller');select memberName from T_member_info where memberId=(select ProviderInfo from T_Goods_info where goodsid='" + goodsId + "' and Datafrom='PersonSeller');"; //DataSet ds = adohelper.ExecuteSqlDataset(strSQL); //if (ds == null || ds.Tables.Count < 2) // return null; //if (ds.Tables[0].Rows.Count > 0) // shopName = ds.Tables[0].Rows[0][0].ToString(); //else // shopName = ds.Tables[1].Rows[0][0].ToString(); ArrayList list = new ArrayList(); AdoHelper adohelper = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance); //搜集表单中的file元素 HttpFileCollection files = Request.Files; //遍历file元素 for (int i = 0; i < files.Count; i++) { HttpPostedFile postedFile = files[i]; HtmlInputCheckBox [] ck = { Checkbox1, Checkbox2, Checkbox3, Checkbox4 }; if (postedFile.FileName != "") { //文件大小 int fileSize = postedFile.ContentLength / 1024; if (fileSize == 0) { fileSize = 1; } //提取文件名 string oldFileName = Path.GetFileName(postedFile.FileName); //提取文件扩展名 string oldFileExt = Path.GetExtension(oldFileName); //重命名文件 string newFileName = Guid.NewGuid().ToString() + oldFileExt; //设置保存目录 string webDirectory = "/upload/goodsadmin/" + DateTime.Now.ToString("yyyyMMdd") + "/"; string saveDirectory = Server.MapPath(webDirectory); if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } //设置保存路径 string savePath = saveDirectory + newFileName; //保存 postedFile.SaveAs(savePath); string savePath2 = savePath; string newFileName2 = newFileName; if (ck[i].Checked) { //System.Drawing.Image nowImg = System.Drawing.Image.FromFile(savePath); System.Drawing.Bitmap nowImg2 = new System.Drawing.Bitmap(savePath); System.Drawing.Bitmap nowImg = new System.Drawing.Bitmap(nowImg2.Width, nowImg2.Height); float x = nowImg.Width - 50; float y = nowImg.Height - 30; System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(nowImg); g.DrawImage(nowImg2, 0, 0); System.Drawing.Font f = new System.Drawing.Font("华文彩云", 12); System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black); g.DrawString("才通天下微信公号", f, b, x, y); f = new System.Drawing.Font("华文琥珀", 12); b = new System.Drawing.SolidBrush(System.Drawing.Color.White); g.DrawString("才通天下微信公号·", f, b, x, y); f.Dispose(); b.Dispose(); g.Dispose(); nowImg2.Dispose(); //savePath2 = webDirectory + newFileName.Replace(oldFileExt, "" + oldFileExt); string nGuid = Guid.NewGuid().ToString(); nGuid = nGuid.Replace(nGuid[new Random().Next(1, 9)], nGuid[new Random().Next(10, 15)]); newFileName2 = nGuid + oldFileExt; savePath2 = webDirectory + newFileName2; MemoryStream ms = new MemoryStream(); nowImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] imgData = ms.ToArray(); File.Delete(savePath); FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite); if (fs != null) { fs.Write(imgData, 0, imgData.Length); fs.Close(); } nowImg.Dispose(); } //缩略图 MakeSmallPic(Server.MapPath(webDirectory + newFileName), Server.MapPath(webDirectory + newFileName.Replace(oldFileExt, ".jpg"))); string goodsSmallPic = webDirectory + newFileName.Replace(oldFileExt, "" + oldFileExt); list.Add(oldFileName + "|" + fileSize + "|" + goodsSmallPic); } } return(list); }
private void ReadBarcode(string sFromFilePath) { string sFromPath = txtFrom.Text; string sFileName = sFromFilePath.Replace((sFromPath + "\\"), ""); System.Drawing.Bitmap oImage = null; try { oImage = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(sFromFilePath); } catch (Exception ex) { if (chkLog.Checked) { txtOutput.AppendText((sFileName + ('\t' + ("Could not open" + "\r\n")))); } this.WriteLog((sFileName + ("," + "Could not open"))); return; } System.Collections.ArrayList barcodes = new System.Collections.ArrayList(); int iScans = 100; DateTime dtStart = DateTime.Now; BarcodeImaging.UseBarcodeZones = chkUseBarcodeZones.Checked; BarcodeImaging.BarcodeType oBarcodeType = BarcodeImaging.BarcodeType.All; switch (cbBarcodeType.Text) { case "Code39": oBarcodeType = BarcodeImaging.BarcodeType.Code39; break; case "Code128": oBarcodeType = BarcodeImaging.BarcodeType.Code128; break; case "EAN": oBarcodeType = BarcodeImaging.BarcodeType.EAN; break; } switch (cbDirection.Text) { case "All": BarcodeImaging.FullScanBarcodeTypes = oBarcodeType; BarcodeImaging.FullScanPage(ref barcodes, oImage, iScans); break; case "Vertical": BarcodeImaging.ScanPage(ref barcodes, oImage, iScans, BarcodeImaging.ScanDirection.Horizontal, oBarcodeType); break; case "Horizontal": BarcodeImaging.ScanPage(ref barcodes, oImage, iScans, BarcodeImaging.ScanDirection.Vertical, oBarcodeType); break; } string sSec = ""; if (chkShowTime.Checked) { sSec = ('\t' + DateTime.Now.Subtract(dtStart).TotalSeconds.ToString("#0.00")); } if ((barcodes.Count == 0)) { if (chkLog.Checked) { txtOutput.AppendText((sFileName + ('\t' + ("Failed" + (sSec + "\r\n"))))); } this.WriteLog((sFileName + ("," + "Failed"))); } else { foreach (object bc in barcodes) { if (chkLog.Checked) { txtOutput.AppendText((sFileName + ('\t' + (bc + (sSec + "\r\n"))))); } this.WriteLog((sFileName + ("," + bc))); } } oImage.Dispose(); }
//ÏÈ´æ·Åµ½ÄÚ´æÖÐ protected void Page_Load(object sender, EventArgs e) { System.Drawing.Image thumbnail_image = null; //ËõÂÔͼ System.Drawing.Image original_image = null; //Ôͼ System.Drawing.Bitmap final_image = null; //×îÖÕͼƬ System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { // Get the data HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); // Calculate the new width and height int width = original_image.Width; int height = original_image.Height; int target_width = 100; int target_height = 100; int new_width, new_height; float target_ratio = (float)target_width / (float)target_height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = target_height; new_width = (int)Math.Floor(image_ratio * (float)target_height); } else { new_height = (int)Math.Floor((float)target_width / image_ratio); new_width = target_width; } new_width = new_width > target_width ? target_width : new_width; new_height = new_height > target_height ? target_height : new_height; // Create the thumbnail // Old way //thumbnail_image = original_image.GetThumbnailImage(new_width, new_height, null, System.IntPtr.Zero); // We don't have to create a Thumbnail since the DrawImage method will resize, but the GetThumbnailImage looks better // I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize it which // can result in a tiny 40x40 thumbnail being stretch up to our target size final_image = new System.Drawing.Bitmap(target_width, target_height); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height)); int paste_x = (target_width - new_width) / 2; int paste_y = (target_height - new_height) / 2; graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */ //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height); graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height); // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo) ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // Store the data in my custom Thumbnail object string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); // Put it all in the Session (initialize the session if necessary) List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>; if (thumbnails == null) { thumbnails = new List <Thumbnail>(); } thumbnails.Add(thumb); Session["file_info"] = thumbnails; Response.StatusCode = 200; Response.Write(thumbnail_id); } catch { // If any kind of error occurs return a 500 Internal Server error Response.StatusCode = 500; Response.Write("An error occured"); Response.End(); } finally { // Clean up if (final_image != null) { final_image.Dispose(); } if (graphic != null) { graphic.Dispose(); } if (original_image != null) { original_image.Dispose(); } if (thumbnail_image != null) { thumbnail_image.Dispose(); } if (ms != null) { ms.Close(); } Response.End(); } }
public void load_tileset(int index, string filename) { bool clearflag = false; if (String.IsNullOrEmpty(filename)) { clearflag = true; } if (!clearflag) { filename = FindTexture(filename); int gid = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, gid); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (float)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (float)TextureWrapMode.ClampToEdge); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(filename); int width_ = bmp.Width; int height_ = bmp.Height; System.Drawing.Imaging.BitmapData bmp_data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0); bmp.UnlockBits(bmp_data); bmp.Dispose(); switch (index) { case 0: if (tilesetA1 != 0) { GL.DeleteTexture(tilesetA1); tilesetA1 = 0; } tilesetA1 = gid; tilesetA1_w = width_; tilesetA1_h = height_; break; case 1: if (tilesetA2 != 0) { GL.DeleteTexture(tilesetA2); tilesetA2 = 0; } tilesetA2 = gid; tilesetA2_w = width_; tilesetA2_h = height_; break; case 2: if (tilesetA3 != 0) { GL.DeleteTexture(tilesetA3); tilesetA3 = 0; } tilesetA3 = gid; tilesetA3_w = width_; tilesetA3_h = height_; break; case 3: if (tilesetA4 != 0) { GL.DeleteTexture(tilesetA4); tilesetA4 = 0; } tilesetA4 = gid; tilesetA4_w = width_; tilesetA4_h = height_; break; case 4: if (tilesetA5 != 0) { GL.DeleteTexture(tilesetA5); tilesetA5 = 0; } tilesetA5 = gid; tilesetA5_w = width_; tilesetA5_h = height_; break; case 5: if (tilesetB != 0) { GL.DeleteTexture(tilesetB); tilesetB = 0; } tilesetB = gid; tilesetB_w = width_; tilesetB_h = height_; break; case 6: if (tilesetC != 0) { GL.DeleteTexture(tilesetC); tilesetC = 0; } tilesetC = gid; tilesetC_w = width_; tilesetC_h = height_; break; case 7: if (tilesetD != 0) { GL.DeleteTexture(tilesetD); tilesetD = 0; } tilesetD = gid; tilesetD_w = width_; tilesetD_h = height_; break; case 8: if (tilesetE != 0) { GL.DeleteTexture(tilesetE); tilesetE = 0; } tilesetE = gid; tilesetE_w = width_; tilesetE_h = height_; break; } } else //empty slot. remove the texture! { switch (index) { case 0: if (tilesetA1 != 0) { GL.DeleteTexture(tilesetA1); tilesetA1 = 0; } break; case 1: if (tilesetA2 != 0) { GL.DeleteTexture(tilesetA2); tilesetA2 = 0; } break; case 2: if (tilesetA3 != 0) { GL.DeleteTexture(tilesetA3); tilesetA3 = 0; } break; case 3: if (tilesetA4 != 0) { GL.DeleteTexture(tilesetA4); tilesetA4 = 0; } break; case 4: if (tilesetA5 != 0) { GL.DeleteTexture(tilesetA5); tilesetA5 = 0; } break; case 5: if (tilesetB != 0) { GL.DeleteTexture(tilesetB); tilesetB = 0; } break; case 6: if (tilesetC != 0) { GL.DeleteTexture(tilesetC); tilesetC = 0; } break; case 7: if (tilesetD != 0) { GL.DeleteTexture(tilesetD); tilesetD = 0; } break; case 8: if (tilesetE != 0) { GL.DeleteTexture(tilesetE); tilesetE = 0; } break; } } }
private void Control_EndPrint(object sender, sdp.PrintEventArgs e) { _controlBitmap?.Dispose(); _controlBitmap = null; Callback.OnPrinted(Widget, e); }
//图片上传 protected void btnSubmit_Click(object sender, EventArgs e) { ClearMethod(); HttpPostedFile hpf = uploadImage.PostedFile; //取得文件名,不含路径 char[] splitChar = { '\\' }; string[] FilenameArray = hpf.FileName.Split(splitChar); string Filename = FilenameArray[FilenameArray.Length - 1].ToLower(); //将用户输入的水印文字处理 //string sMessage = lineStr(TextBox3.Text.Trim().ToString(), 20); if (hpf.FileName.Length < 1) { panelAttention.Visible = true; lbAttention.Text = "请选择你要上传的图片文件"; return; } if (hpf.ContentType != "image/jpeg" && hpf.ContentType != "image/gif") { panelAttention.Visible = true; lbAttention.Text = "只允许上传JPEG GIF文件"; return; } else { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(DateTime.Now.Year.ToString()); sb.Append(DateTime.Now.Month.ToString()); sb.Append(DateTime.Now.Day.ToString()); sb.Append(DateTime.Now.Hour.ToString()); sb.Append(DateTime.Now.Minute.ToString()); sb.Append(DateTime.Now.Second.ToString()); if (Filename.ToLower().EndsWith("gif")) { sb.Append(".gif"); } else if (Filename.ToLower().EndsWith("jpg")) { sb.Append(".jpg"); } else if (Filename.ToLower().EndsWith("jpeg")) { sb.Append(".jpeg"); } Filename = sb.ToString(); //保存图片到服务器上 try { hpf.SaveAs(Server.MapPath("~") + "/images/onsale/wear/big_" + Filename); } catch (Exception ee) { panelAttention.Visible = true; lbAttention.Text = "上传图片失败,原因:" + ee.Message; return; } //生成缩略图 //原始图片名称 string originalFilename = hpf.FileName; //生成高质量图片名称 string strFile = Server.MapPath("~") + "/images/onsale/wear/small/small_" + Filename; //从文件获取图片对象 System.Drawing.Image image = System.Drawing.Image.FromStream(hpf.InputStream, true); Double Width = Double.Parse(TextBox1.Text.Trim()); Double Height = Double.Parse(TextBox2.Text.Trim()); System.Double newWidth, newHeight; if (image.Width > image.Height) { newWidth = Width; newHeight = image.Height * (newWidth / image.Width); } else { newHeight = Height; newWidth = image.Width * (newHeight / image.Height); } if (newWidth > Width) { newWidth = Width; } if (newHeight > Height) { newHeight = Height; } System.Drawing.Size size = new System.Drawing.Size((int)newWidth, (int)newHeight); //设置图片的宽度和高度 System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height); //新建bmp图片 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //新建画板 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //制定高质量插值法 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量、低速度呈现平滑程度 g.Clear(System.Drawing.Color.White); //清空画布 //在制定位置画图 g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel); //文字水印 System.Drawing.Graphics testGrahpics = System.Drawing.Graphics.FromImage(bitmap); System.Drawing.Font font = new System.Drawing.Font("宋体", 10); System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); //分行 string sInput = TextBox3.Text.Trim().ToString(); //获取输入的水印文字 int coloum = Convert.ToInt32(TextBox4.Text); //获取每行的字符数 //利用循环,来依次输出 for (int i = 0, j = 0; i < sInput.Length; i += coloum, j++) { //若要修改水印文字在照片上的位置,可将20修改成你想要的任何值 if (j != sInput.Length / coloum) { string s = sInput.Substring(i, coloum); testGrahpics.DrawString(s, font, brush, 20, 20 * (i / coloum + 1)); } else { string s = sInput.Substring(i, sInput.Length % coloum); testGrahpics.DrawString(s, font, brush, 20, 20 * (j + 1)); } } testGrahpics.Dispose(); //保存缩略图c try { bitmap.Save(strFile, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { paneInfo.Visible = true; lbInfo.Text = "保存缩略图失败" + ex.Message; } //释放资源 g.Dispose(); bitmap.Dispose(); image.Dispose(); } Entity.PicturesItem pic = new Entity.PicturesItem(); pic.setItemID(int.Parse(lbItemId.Text)); // pic.setIntImageID(int.Parse(lbImageID.Text)); pic.setBigImg("images/onsale/wear/big_" + Filename); pic.setSmallImg("images/onsale/wear/small/small_" + Filename); pic.setAlt(""); switch (btnSubmit.Text) { case "新增": //新增模式 if (picture.InserItemsPic(pic)) { panelSuccess.Visible = true; lbSuccess.Text = "新增图片成功!"; } else { panelError.Visible = true; lbError.Text = "新增图片失败!"; } break; case "修改": //修改模式 //int.Parse(lbImageID.Text), int.Parse(lbItemId.Text), "images/onsale/wear/big_" + Filename, "images/onsale/wear/small/small_" + Filename, "" if (picture.UpdatePicByID(pic)) { panelSuccess.Visible = true; lbSuccess.Text = "修改图片成功!"; } else { panelError.Visible = true; lbError.Text = "修改图片失败!"; } break; } }
public void GlobalCleanup() { _drawingBitmap?.Dispose(); _container.Dispose(); _imageSharp?.Dispose(); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }