当前位置: 首页>>代码示例>>C#>>正文


C# Bitmap.Dispose方法代码示例

本文整理汇总了C#中System.Drawing.Bitmap.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Bitmap.Dispose方法的具体用法?C# Bitmap.Dispose怎么用?C# Bitmap.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Drawing.Bitmap的用法示例。


在下文中一共展示了Bitmap.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: button3_Click

 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);
         }
     }
 }
开发者ID:winterheart,项目名称:game-utilities,代码行数:25,代码来源:Form1.cs

示例2: ValidatePicture

        /// <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;
                }
            }
        }
开发者ID:tsubik,项目名称:SFASystem,代码行数:34,代码来源:ImageHelper.cs

示例3: Parse

		/// <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;
			}
		}
开发者ID:JakubVanek,项目名称:openBVE-1,代码行数:64,代码来源:Plugin.Parser.cs

示例4: GLTextureObject

        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);
        }
开发者ID:AugustoAngeletti,项目名称:blockspaces,代码行数:27,代码来源:GLTextureObject.cs

示例5: TextureFromBitmap

        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;
        }
开发者ID:yong-ja,项目名称:starodyssey,代码行数:29,代码来源:ImageHelper.cs

示例6: GenerateThumbImg

        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;
            }
        }
开发者ID:feitianxiaodai,项目名称:rental,代码行数:31,代码来源:1436850790$ImgHelper.cs

示例7: CreateFromHidden

        /// <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;
        }
开发者ID:Nucs,项目名称:nlib,代码行数:34,代码来源:ScreenShot.cs

示例8: CreateCheckCodeImage

 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();
         }
     }
 }
开发者ID:KevinXu816,项目名称:ExamineSystem,代码行数:33,代码来源:validate.aspx.cs

示例9: DrawEffectImage

        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);
            }
        }
开发者ID:chanpi,项目名称:FormSample,代码行数:60,代码来源:EPL2RSlidingEffect.cs

示例10: DrawInitBitmap

        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();
        }
开发者ID:gawallsibya,项目名称:BIT_MFC-CShap-DotNet,代码行数:30,代码来源:Form1.cs

示例11: CaptchaResult

        /// <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");
            }
        }
开发者ID:jorgebay,项目名称:nearforums,代码行数:35,代码来源:CaptchaHelper.cs

示例12: DecodeFromPointer

        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;
        }
开发者ID:kblc,项目名称:ExcelConverter,代码行数:26,代码来源:SimpleDecoder.cs

示例13: GetCaptchaImage

 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();
     }
 }
开发者ID:janessabautista123,项目名称:Thesis,代码行数:27,代码来源:Utility.cs

示例14: ProcessEMF

 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();
         }
     }
 }
开发者ID:NelsonSantos,项目名称:fyiReporting-Android,代码行数:26,代码来源:EMF.cs

示例15: Form1_DragDrop

        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);
        }
开发者ID:miwarin,项目名称:kancolle-hensei,代码行数:27,代码来源:Form1.cs


注:本文中的System.Drawing.Bitmap.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。