Esempio n. 1
0
 protected override void InitGraphics()
 {
     Logger.Info("Gfx", $"Init Graphics {viewWidth} x {viewHeight} scale = {viewScale}");
     gfx?.Dispose();
     view?.Dispose();
     view = new System.Drawing.Bitmap(viewWidth, viewHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     gfx  = System.Drawing.Graphics.FromImage(view);
     InitGraphics(gfx);
 }
Esempio n. 2
0
        ///   <summary>
        ///   从图片中截取部分生成新图
        ///   </summary>
        ///   <param   name="sFromFilePath">原始图片</param>
        ///   <param   name="saveFilePath">生成新图</param>
        ///   <param   name="width">截取图片宽度</param>
        ///   <param   name="height">截取图片高度</param>
        ///   <param   name="spaceX">截图图片X坐标</param>
        ///   <param   name="spaceY">截取图片Y坐标</param>
        public void CaptureImage(string sFromFilePath, string saveFilePath, int width, int height, int spaceX, int spaceY, string tarimg, string targetID)
        {
            //载入底图
            System.Drawing.Image  fromImage = System.Drawing.Image.FromFile(sFromFilePath);
            System.Drawing.Bitmap bitmap    = new System.Drawing.Bitmap(width, height);
            //创建作图区域
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);
            //截取原图相应区域写入作图区
            graphic.DrawImage(fromImage, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(spaceX, spaceY, width, height), System.Drawing.GraphicsUnit.Pixel);
            //从作图区生成新图
            System.Drawing.Image saveImage = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap());
            //保存图象
            saveImage.Save(saveFilePath, ImageFormat.Jpeg);
            bitmap.Dispose();
            graphic.Dispose();
            saveImage.Dispose();
            fromImage.Dispose();

            //string delTarget = tarimg.Replace("nail.", ".");
            //FileHelper.DeleteFile(new List<string> { delTarget });//删除原图
            FileHelper.DeleteFile(new List <string> {
                tarimg
            });                                                //删除原图

            string delTarget = saveFilePath.Replace(Server.MapPath("/"), "");

            //FileInfo fileInfo = new FileInfo(saveFilePath);
            //fileInfo.MoveTo(sFromFilePath);

            if (makeNail == 1)//是否需要生成缩略图
            {
                string makeFile = string.Empty;
                //if (targetType == 0)
                //{
                Dictionary <int, int> dic = new Dictionary <int, int>();
                if (tableID == ProductBLL.TableID)
                {
                    foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.Product))
                    {
                        dic.Add(phototype.Width, phototype.Height);
                    }
                    if (!dic.ContainsKey(90))
                    {
                        dic.Add(90, 90);                          //后台商品列表默认使用尺寸(如果不存在则手动添加)
                    }
                }
                else if (tableID == ProductBrandBLL.TableID)
                {
                    dic.Add(88, 31);
                }
                else if (tableID == ThemeActivityBLL.TableID)
                {
                    dic.Add(300, 150);
                }
                else if (tableID == ArticleBLL.TableID)
                {
                    dic.Add(90, 90);    //后台列表缩略图
                    dic.Add(200, 150);  //前台列表缩略图
                }
                else if (tableID == ProductPhotoBLL.TableID)
                {
                    foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.ProductPhoto))
                    {
                        dic.Add(phototype.Width, phototype.Height);
                    }
                    if (!dic.ContainsKey(75))
                    {
                        dic.Add(75, 75);                          //后台商品图集默认使用尺寸(如果不存在则手动添加)
                    }
                }
                if (dic.Count > 0)
                {
                    foreach (KeyValuePair <int, int> kv in dic)
                    {
                        //string nailStr = delTarget.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString());
                        string nailStr = tarimg.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString());

                        FileHelper.DeleteFile(new List <string> {
                            nailStr
                        });                                                     //删除原有缩略图
                        //makeFile = nailStr;
                        makeFile = delTarget.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString());
                        ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(delTarget), ServerHelper.MapPath(makeFile), kv.Key, kv.Value, ThumbnailType.InBox);
                    }
                }
                //}
                //else
                //{

                //    Hashtable ht = new Hashtable();
                //    if (tableID == ProductPhotoBLL.TableID)
                //    {
                //        foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.ProductPhoto))
                //        {
                //            ht.Add(phototype.Width, phototype.Height);
                //        }
                //        if (!ht.ContainsKey(75)) ht.Add(75, 75);//后台商品图集默认使用尺寸(如果不存在则手动添加)
                //    }
                //    else
                //    {
                //        ht.Add("75", "75");
                //        ht.Add("350", "350");
                //    }
                //    foreach (DictionaryEntry de in ht)
                //    {
                //        string nailStr = delTarget.Replace("Original", de.Key + "-" + de.Value);
                //        FileHelper.DeleteFile(new List<string> { nailStr });//删除原有缩略图
                //        makeFile = nailStr;
                //        ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(delTarget), ServerHelper.MapPath(makeFile), Convert.ToInt32(de.Key), Convert.ToInt32(de.Value), ThumbnailType.InBox);
                //    }
                //}
            }
            //parent.layer.close(index);
            string strp_img2 = saveFilePath.Substring(saveFilePath.LastIndexOf('/'), saveFilePath.Length - saveFilePath.LastIndexOf('/'));

            if (targetType == 1)//产品多图
            {
                if (ProductID <= 0)
                {//添加
                    //Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name); parent.$('#" + targetID + ">img').attr('src','" + delTarget + "'); parent.layer.close(index);</script>");
                    string _str = "<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>";
                    //Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').firstChild.src='" + delTarget + "';window.parent.o('" + targetID + "').getElementsByName('ProductPhoto')[0].value='" + _name + "|" + delTarget + "' ; parent.layer.close(index);</script>");
                    Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>");
                }
                else
                {
                    ProductPhotoInfo productPhoto = ProductPhotoBLL.Read(ProductPhotoID, ProStyle);
                    productPhoto.ImageUrl = delTarget;
                    ProductPhotoBLL.Update(productPhoto);
                    string _str = "<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>";

                    //Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').firstChild.src='" + delTarget + "';$('#" + targetID + "').find('.cut').attr('href','javascript:loadCut(\"" + delTarget + "\",\"" + targetID + "\",\"" + ProductPhotoID + "\")');parent.layer.close(index);</script>");
                    Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').value='" + delTarget + "';window.parent.o('firstPhoto').src='" + delTarget + "';parent.layer.close(index); </script>");
            }
        }
Esempio n. 3
0
        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 "YS":    //不改变图片大小直接压缩
                towidth  = originalImage.Width;
                toheight = originalImage.Height;
                break;

            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;

            case "C":                                                                                                     //按原图比例缩放
                if (((double)originalImage.Width < (double)towidth) && ((double)originalImage.Height < (double)toheight)) //图片小于外框尺寸,不做处理
                {
                    ow = originalImage.Width;
                    oh = originalImage.Height;
                    x  = (towidth - ow) / 2;
                    y  = (toheight - oh) / 2;
                }
                else
                {
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x  = 0;
                        y  = (originalImage.Height - oh) / 2;
                    }
                    else
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y  = 0;
                        x  = (originalImage.Width - ow) / 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.White);

            //在指定地位并且按指定大小绘制原图片的指定部分
            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();
            }
        }
Esempio n. 4
0
        /// <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)
        {
            using (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;
                if (originalImage.Width <= width && originalImage.Height <= height && mode.ToUpper() != "CUT" && mode.ToUpper() != "CUTA")
                {
                    File.Copy(originalImagePath, thumbnailPath, true);
                    return;
                }
                switch (mode.ToUpper())
                {
                case "HW":    //指定高宽缩放(可能变形)
                    break;

                case "W":    //指定宽,高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;

                case "H":    //指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;

                case "CUTA":    //指定高宽裁减(不变形)
                    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;

                case "CUT":    //指定高宽裁减(不变形)自定义
                               //if (ow <= towidth && oh <= toheight)
                               //{
                               //    x = -(towidth - ow) / 2;
                               //    y = -(toheight - oh) / 2;
                               //    ow = towidth;
                               //    oh = toheight;
                               //}
                               //else
                               //{
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x  = 0;
                        y  = (originalImage.Height - oh) / 2;
                    }
                    else
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y  = 0;
                        x  = (originalImage.Width - ow) / 2;
                    }
                    //if (ow > oh)//宽大于高
                    //{
                    //    x = 0;
                    //    y = -(ow - oh) / 2;
                    //    oh = ow;
                    //}
                    //else//高大于宽
                    //{
                    //    y = 0;
                    //    x = -(oh - ow) / 2;
                    //    ow = oh;
                    //}
                    //}
                    break;

                case "CUT1":
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    else
                    {
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                    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.CompositingMode   = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                //g.Clear(System.Drawing.Color.Transparent);
                g.Clear(System.Drawing.Color.White);
                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                            new System.Drawing.Rectangle(x, y, ow, oh),
                            System.Drawing.GraphicsUnit.Pixel);
                try
                {
                    //string fileExtension = Path.GetExtension(originalImagePath).ToLower();
                    //switch (fileExtension)
                    //{
                    //    case ".jpg":
                    //        //以jpg格式保存缩略图
                    //        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    //    case ".jpeg":
                    //        //以jpg格式保存缩略图
                    //        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    //    case ".gif":
                    //        //以jpg格式保存缩略图
                    //        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    //    case ".png":
                    //        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                    //}
                    //以jpg格式保存缩略图
                    //bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ImageCodecInfo ici;
                    System.Drawing.Imaging.Encoder enc;
                    EncoderParameter  ep;
                    EncoderParameters epa;
                    //   Initialize   the   necessary   objects
                    ici = GetEncoderInfo("image/jpeg");
                    enc = System.Drawing.Imaging.Encoder.Quality;//设置保存质量
                    epa = new EncoderParameters(1);
                    //   Set   the   compression   level
                    ep           = new EncoderParameter(enc, 90L);//质量等级为90%
                    epa.Param[0] = ep;
                    bitmap.Save(thumbnailPath, ici, epa);
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="photoWidth">缩略图宽度</param>
        /// <param name="photoHeight">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        /// <code>HW:指定高宽缩放(可能变形)</code>
        /// <code>W:指定宽,高按比例  </code>
        /// <code>H:指定高,宽按比例</code>
        /// <code>CUT:指定高宽裁减(不变形) </code>
        /// <code>FILL:填充</code>
        /// <param name="retwidth">返回缩略图宽度</param>
        /// <param name="retheight">返回缩略图高度</param>
        /// <returns></returns>
        public static bool LocalImage2Thumbs2(string originalImagePath, string thumbnailPath, int photoWidth, int photoHeight, string mode, ref int retwidth, ref int retheight)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            #region 开始画图
            int lastPhotoWidth  = photoWidth;  //最后缩略图的宽度
            int lastPhotoHeight = photoHeight; //最后缩略图的高度

            int toWidth  = photoWidth;         //原图片被压缩的宽度
            int toHeight = photoHeight;        //原图片被压缩的高度

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            int bg_x = 0;
            int bg_y = 0;
            switch (mode.ToUpper())
            {
            case "FILL":    //压缩填充至指定区域
                toHeight = photoHeight;
                toWidth  = toHeight * ow / oh;
                if (toWidth > photoWidth)
                {
                    toHeight = toHeight * photoWidth / toWidth;
                    toWidth  = photoWidth;
                }
                bg_x = (photoWidth - toWidth) / 2;
                bg_y = (photoHeight - toHeight) / 2;
                break;

            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toHeight = lastPhotoHeight = originalImage.Height * photoWidth / originalImage.Width;
                break;

            case "H":    //指定高,宽按比例
                toWidth = lastPhotoWidth = originalImage.Width * photoHeight / originalImage.Height;
                break;

            case "CUT":    //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)lastPhotoWidth / (double)lastPhotoHeight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * lastPhotoWidth / lastPhotoHeight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * photoHeight / lastPhotoWidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }
            if (photoWidth > originalImage.Width)
            {
                toWidth  = lastPhotoWidth = originalImage.Width;   //最后缩略图的宽度
                toHeight = lastPhotoHeight = originalImage.Height; //最后缩略图的高度
            }
            retwidth  = lastPhotoWidth;
            retheight = lastPhotoHeight;
            System.Drawing.Image    bitmap = new System.Drawing.Bitmap(lastPhotoWidth, lastPhotoHeight); //新建一个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.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
            g.Clear(System.Drawing.Color.White);                                                    //白色
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, toWidth, toHeight), //在指定位置并且按指定大小绘制原图片的指定部分
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                bitmap.Dispose();
                g.Dispose();
            }
            #endregion
            originalImage.Dispose();
            return(true);
        }
        /// <summary>
        /// Initializes the media events.
        /// </summary>
        private void InitializeMediaEvents()
        {
            Media.MediaOpened     += Media_MediaOpened;
            Media.MediaOpening    += Media_MediaOpening;
            Media.MediaFailed     += Media_MediaFailed;
            Media.MessageLogged   += Media_MessageLogged;
            Media.PropertyChanged += Media_PropertyChanged;
            Unosquare.FFME.MediaElement.FFmpegMessageLogged += MediaElement_FFmpegMessageLogged;

#if HANDLE_RENDERING_EVENTS
            #region Audio and Video Frame Rendering Variables

            System.Drawing.Bitmap   overlayBitmap   = null;
            System.Drawing.Graphics overlayGraphics = null;
            var overlayTextFont      = new System.Drawing.Font("Arial", 14, System.Drawing.FontStyle.Bold);
            var overlayTextFontBrush = System.Drawing.Brushes.WhiteSmoke;
            var overlayTextOffset    = new System.Drawing.PointF(12, 8);
            var overlayBackBuffer    = IntPtr.Zero;

            var vuMeterLeftPen  = new System.Drawing.Pen(System.Drawing.Color.OrangeRed, 12);
            var vuMeterRightPen = new System.Drawing.Pen(System.Drawing.Color.GreenYellow, 12);
            var vuMeterRmsLock  = new object();
            var vuMeterLeftRms  = new SortedDictionary <TimeSpan, double>();
            var vuMeterRightRms = new SortedDictionary <TimeSpan, double>();

            var         vuMeterLeftValue   = 0d;
            var         vuMeterRightValue  = 0d;
            const float vuMeterLeftOffset  = 16;
            const float vuMeterTopOffset   = 50;
            const float vuMeterScaleFactor = 20; // RMS * pixel factor = the length of the VU meter lines

            #endregion

            #region Rendering Event Examples

            Media.RenderingVideo += (s, e) =>
            {
                #region Create the overlay buffer to work with

                if (overlayBackBuffer != e.Bitmap.BackBuffer)
                {
                    lock (vuMeterRmsLock)
                    {
                        vuMeterLeftRms.Clear();
                        vuMeterRightRms.Clear();
                    }

                    if (overlayGraphics != null)
                    {
                        overlayGraphics.Dispose();
                    }
                    if (overlayBitmap != null)
                    {
                        overlayBitmap.Dispose();
                    }

                    overlayBitmap = new System.Drawing.Bitmap(
                        e.Bitmap.PixelWidth, e.Bitmap.PixelHeight, e.Bitmap.BackBufferStride,
                        System.Drawing.Imaging.PixelFormat.Format24bppRgb, e.Bitmap.BackBuffer);

                    overlayBackBuffer = e.Bitmap.BackBuffer;
                    overlayGraphics   = System.Drawing.Graphics.FromImage(overlayBitmap);
                    overlayGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                }

                #endregion

                #region Read the instantaneous RMS of the audio

                lock (vuMeterRmsLock)
                {
                    vuMeterLeftValue  = vuMeterLeftRms.Where(kvp => kvp.Key > Media.Position).Select(kvp => kvp.Value).FirstOrDefault();
                    vuMeterRightValue = vuMeterRightRms.Where(kvp => kvp.Key > Media.Position).Select(kvp => kvp.Value).FirstOrDefault();

                    // do some cleanup so the dictionary does not grow too big.
                    if (vuMeterLeftRms.Count > 256)
                    {
                        var keysToRemove = vuMeterLeftRms.Keys.Where(k => k < Media.Position).OrderBy(k => k).ToArray();
                        foreach (var k in keysToRemove)
                        {
                            vuMeterLeftRms.Remove(k);
                            vuMeterRightRms.Remove(k);

                            if (vuMeterLeftRms.Count < 256)
                            {
                                break;
                            }
                        }
                    }
                }

                #endregion

                #region Draw the text and the VU meter

                e.Bitmap.Lock();
                var differenceMillis = TimeSpan.FromTicks(e.Clock.Ticks - e.StartTime.Ticks).TotalMilliseconds;

                overlayGraphics.DrawString($"Clock: {e.StartTime.TotalSeconds:00.000} | Skew: {differenceMillis:00.000} | PN: {e.PictureNumber}",
                                           overlayTextFont, overlayTextFontBrush, overlayTextOffset);

                // draw a simple VU meter
                overlayGraphics.DrawLine(vuMeterLeftPen,
                                         vuMeterLeftOffset, vuMeterTopOffset,
                                         vuMeterLeftOffset + 5 + (Convert.ToSingle(vuMeterLeftValue) * vuMeterScaleFactor), vuMeterTopOffset);

                overlayGraphics.DrawLine(vuMeterRightPen,
                                         vuMeterLeftOffset, vuMeterTopOffset + 20,
                                         vuMeterLeftOffset + 5 + (Convert.ToSingle(vuMeterRightValue) * vuMeterScaleFactor), vuMeterTopOffset + 20);

                e.Bitmap.AddDirtyRect(new Int32Rect(0, 0, e.Bitmap.PixelWidth, e.Bitmap.PixelHeight));
                e.Bitmap.Unlock();

                #endregion
            };

            Media.RenderingAudio += (s, e) =>
            {
                // The buffer contains all the samples
                var buffer = new byte[e.BufferLength];
                Marshal.Copy(e.Buffer, buffer, 0, e.BufferLength);

                // We need to split the samples into left and right samples
                var leftSamples  = new double[e.SamplesPerChannel];
                var rightSamples = new double[e.SamplesPerChannel];

                // Iterate through the buffer
                var isLeftSample  = true;
                var sampleIndex   = 0;
                var samplePercent = default(double);

                for (var i = 0; i < e.BufferLength; i += e.BitsPerSample / 8)
                {
                    samplePercent = 100d * Math.Abs((double)((short)(buffer[i] | (buffer[i + 1] << 8)))) / (double)short.MaxValue;

                    if (isLeftSample)
                    {
                        leftSamples[sampleIndex] = samplePercent;
                    }
                    else
                    {
                        rightSamples[sampleIndex] = samplePercent;
                    }

                    sampleIndex += !isLeftSample ? 1 : 0;
                    isLeftSample = !isLeftSample;
                }

                // Compute the RMS of the samples and save it for the given point in time.
                lock (vuMeterRmsLock)
                {
                    // The VU meter should show the audio RMS, we compute it and save it in a dictionary.
                    vuMeterLeftRms[e.StartTime]  = Math.Sqrt((1d / leftSamples.Length) * (leftSamples.Sum(n => n)));
                    vuMeterRightRms[e.StartTime] = Math.Sqrt((1d / rightSamples.Length) * (rightSamples.Sum(n => n)));
                }
            };

            Media.RenderingSubtitles += (s, e) =>
            {
                // a simple example of suffixing subtitles
                if (e.Text != null && e.Text.Count > 0)
                {
                    e.Text[0] = $"{e.Text[0]}\r\n(subtitles)";
                }
            };

            #endregion
#endif
        }
Esempio n. 7
0
        public System.Drawing.Image GetSizedImage(int width, int height)
        {
            if ((Sizing == Rdl.Engine.Image.ImageSizingEnum.Clip || Sizing == Rdl.Engine.Image.ImageSizingEnum.Fit || Sizing == Rdl.Engine.Image.ImageSizingEnum.FitProportional) &&
                width > 0 && height > 0)
            {
                // Create a new bitmap for the image
                System.Drawing.Bitmap bm = null;

                System.Drawing.Rectangle sourceRect = System.Drawing.Rectangle.Empty;
                System.Drawing.Rectangle destRect   = System.Drawing.Rectangle.Empty;

                if (Sizing == Rdl.Engine.Image.ImageSizingEnum.Clip)
                {
                    bm = new System.Drawing.Bitmap(width, height);

                    // Create the clipping rectangles
                    int xAdj = (width > imageData.Width) ? 0 : ((imageData.Width - width) / 2);
                    int yAdj = (height > imageData.Height) ? 0 : ((imageData.Height - height) / 2);
                    sourceRect = new System.Drawing.Rectangle(xAdj, yAdj, imageData.Width - xAdj, imageData.Height - yAdj);

                    xAdj     = (imageData.Width > width) ? 0 : ((width - imageData.Width) / 2);
                    yAdj     = (imageData.Height > height) ? 0 : ((height - imageData.Height) / 2);
                    destRect = new System.Drawing.Rectangle(xAdj, yAdj, width - xAdj, height - yAdj);
                }
                if (Sizing == Rdl.Engine.Image.ImageSizingEnum.Fit)
                {
                    bm = new System.Drawing.Bitmap(width, height);

                    // Resize the whole image to the full size of the box.
                    sourceRect = new System.Drawing.Rectangle(0, 0, imageData.Width, imageData.Height);
                    destRect   = new System.Drawing.Rectangle(0, 0, width, height);
                }
                if (Sizing == Rdl.Engine.Image.ImageSizingEnum.FitProportional)
                {
                    // Resize the image proportionally to fit the box.
                    sourceRect = new System.Drawing.Rectangle(0, 0, imageData.Width, imageData.Height);
                    int   xAdj = 0;
                    int   yAdj = 0;
                    float f1   = (float)imageData.Width / (float)imageData.Height;
                    float f2   = (float)width / (float)height;
                    if (f1 > f2)
                    {
                        yAdj = (height - (int)((float)width / f1));
                    }
                    else
                    {
                        xAdj = (width - (int)((float)height * f1));
                    }

                    bm       = new System.Drawing.Bitmap(width - xAdj, height - yAdj);
                    destRect = new System.Drawing.Rectangle(0, 0, width - xAdj, height - yAdj);
                }

                // Draw the image onto the new bitmap.
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
                g.DrawImage(imageData, destRect, sourceRect, System.Drawing.GraphicsUnit.Pixel);
                g.Dispose();

                return(bm);
            }
            else if (ImageRepeat != Rdl.Engine.BackgroundImage.ImageRepeatEnum.NoRepeat && width > 0 && height > 0)
            {
                // If the image is repeated and we know the space that it is going to be repeated into
                // then draw multiple copies of the image into a new sized bitmap

                // Create a new bitmap for the image
                System.Drawing.Bitmap   bm = new System.Drawing.Bitmap(width, height);;
                System.Drawing.Graphics g  = System.Drawing.Graphics.FromImage(bm);

                System.Drawing.Rectangle sourceRect = System.Drawing.Rectangle.Empty;
                System.Drawing.Rectangle destRect   = System.Drawing.Rectangle.Empty;

                int  x = 0; int y = 0;
                bool done = false;
                while (!done)
                {
                    sourceRect = new System.Drawing.Rectangle(0, 0,
                                                              Math.Min(imageData.Width, width - x),
                                                              Math.Min(imageData.Height, height - y));
                    destRect = new System.Drawing.Rectangle(x, y,
                                                            Math.Min(imageData.Width, width - x),
                                                            Math.Min(imageData.Height, height - y));

                    // Draw the image onto the new bitmap.
                    g.DrawImage(imageData, destRect, sourceRect, System.Drawing.GraphicsUnit.Pixel);

                    if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.Repeat ||
                        ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.RepeatX)
                    {
                        x += imageData.Width;
                        if (x >= width)
                        {
                            if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.Repeat)
                            {
                                x  = 0;
                                y += imageData.Height;
                            }
                            else
                            {
                                done = true;
                            }
                        }
                    }

                    if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.RepeatY)
                    {
                        y += imageData.Height;
                    }

                    if (y >= height)
                    {
                        done = true;
                    }
                }
                g.Dispose();
                return(bm);
            }
            else
            {
                return(imageData);
            }
        }
Esempio n. 8
0
        public static Bitmap LoadFromFile(RenderTarget renderTarget, string file)
        {
            // Loads from file using System.Drawing.Image
            if (file != "invalid")
            {
                using (var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(file))
                {
                    var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                    var size             = new Size2(bitmap.Width, bitmap.Height);

                    // Transform pixels from BGRA to RGBA
                    var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    int stride     = bitmapData.Stride;
                    int d2d_strie  = bitmap.Height * bitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(d2d_strie, true, true))
                    {
                        // Lock System.Drawing.Bitmap
                        long length = bitmap.Height * stride;
                        if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                        {
                            unsafe
                            {
                                byte *rgbValues = (byte *)bitmapData.Scan0.ToPointer();
                                int   rgba;
                                for (int i = 0; i < length; i += 4)
                                {
                                    rgba = rgbValues[i + 2] | (rgbValues[i + 1] << 8) | (rgbValues[i] << 16) | (rgbValues[i + 3] << 24);
                                    tempStream.Write(rgba);
                                }
                            }
                        }
                        if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
                        {
                            unsafe
                            {
                                byte  full      = 255;
                                byte *rgbValues = (byte *)bitmapData.Scan0.ToPointer();
                                int   rgba;
                                for (int i = 0; i < length; i += 3)
                                {
                                    rgba = rgbValues[i + 2] | (rgbValues[i + 1] << 8) | (rgbValues[i] << 16) | (full << 24);
                                    //rgba = (full) | (rgbValues[i] << 8) | (rgbValues[i + 1] << 16) | (rgbValues[i + 2] << 24);
                                    tempStream.Write(rgba);
                                }
                            }
                        }

                        bitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;
                        Bitmap bitmap_d2d = new Bitmap(renderTarget, size, tempStream, d2d_strie / bitmap.Height, bitmapProperties);
                        bitmap.Dispose();
                        tempStream.Dispose();
                        return(bitmap_d2d);
                    }
                }
            }
            else
            {
                System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(200, 100, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

                var pen = new System.Drawing.Pen(System.Drawing.Brushes.Red, 10f);
                graphics.Clear(System.Drawing.Color.White);
                graphics.DrawLine(pen, 0, 0, 200, 100);
                graphics.DrawLine(pen, 0, 100, 200, 0);
                graphics.Dispose();

                var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                var size             = new Size2(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                int stride     = bitmapData.Stride;
                int d2d_strie  = bitmap.Height * bitmap.Width * sizeof(int);
                using (var tempStream = new DataStream(d2d_strie, true, true))
                {
                    // Lock System.Drawing.Bitmap
                    long length = bitmap.Height * stride;
                    if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                    {
                        unsafe
                        {
                            byte *rgbValues = (byte *)bitmapData.Scan0.ToPointer();
                            int   rgba;
                            for (int i = 0; i < length; i += 4)
                            {
                                rgba = rgbValues[i + 2] | (rgbValues[i + 1] << 8) | (rgbValues[i] << 16) | (rgbValues[i + 3] << 24);
                                tempStream.Write(rgba);
                            }
                        }
                    }
                    if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
                    {
                        unsafe
                        {
                            byte  full      = 255;
                            byte *rgbValues = (byte *)bitmapData.Scan0.ToPointer();
                            int   rgba;
                            for (int i = 0; i < length; i += 3)
                            {
                                rgba = rgbValues[i + 2] | (rgbValues[i + 1] << 8) | (rgbValues[i] << 16) | (full << 24);
                                //rgba = (full) | (rgbValues[i] << 8) | (rgbValues[i + 1] << 16) | (rgbValues[i + 2] << 24);
                                tempStream.Write(rgba);
                            }
                        }
                    }

                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;
                    Bitmap bitmap_d2d = new Bitmap(renderTarget, size, tempStream, d2d_strie / bitmap.Height, bitmapProperties);
                    bitmap.Dispose();
                    tempStream.Dispose();
                    pen.Dispose();
                    return(bitmap_d2d);
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Provides examples for rendering events
        /// </summary>
        private void BindMediaRenderingEvents()
        {
            if (System.Diagnostics.Debugger.IsAttached == false)
            {
                return;
            }

            #region Audio and Video Frame Rendering Variables

            // Setup GDI+ graphics
            System.Drawing.Bitmap   overlayBitmap   = null;
            System.Drawing.Graphics overlayGraphics = null;
            var overlayTextFont      = new System.Drawing.Font("Courier New", 14, System.Drawing.FontStyle.Bold);
            var overlayTextFontBrush = System.Drawing.Brushes.WhiteSmoke;
            var overlayTextOffset    = new System.Drawing.PointF(12, 8);
            var overlayBackBuffer    = IntPtr.Zero;

            var drawVuMeterLeftPen  = new System.Drawing.Pen(System.Drawing.Color.OrangeRed, 12);
            var drawVuMeterRightPen = new System.Drawing.Pen(System.Drawing.Color.GreenYellow, 12);
            var drawVuMeterClock    = TimeSpan.Zero;
            var drawVuMeterRmsLock  = new object();

            var      drawVuMeterLeftValue     = 0d;
            var      drawVuMeterRightValue    = 0d;
            double[] drawVuMeterLeftSamples   = null;
            double[] rdrawVuMeterRightSamples = null;

            const float drawVuMeterLeftOffset  = 36;
            const float drawVuMeterTopSpacing  = 21;
            const float drawVuMeterTopOffset   = 81;
            const float drawVuMeterMinWidth    = 5;
            const float drawVuMeterScaleFactor = 20; // RMS * pixel factor = the length of the VU meter lines

            #endregion

            #region Rendering Event Examples

            Media.RenderingVideo += (s, e) =>
            {
                #region Create the overlay buffer to work with

                if (overlayBackBuffer != e.Bitmap.Scan0)
                {
                    lock (drawVuMeterRmsLock)
                    {
                        drawVuMeterLeftValue  = 0;
                        drawVuMeterRightValue = 0;
                    }

                    if (overlayGraphics != null)
                    {
                        overlayGraphics.Dispose();
                    }
                    if (overlayBitmap != null)
                    {
                        overlayBitmap.Dispose();
                    }

                    overlayBitmap = e.Bitmap.CreateDrawingBitmap();

                    overlayBackBuffer = e.Bitmap.Scan0;
                    overlayGraphics   = System.Drawing.Graphics.FromImage(overlayBitmap);
                    overlayGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                }

                #endregion

                #region Draw the text and the VU meter

                double differenceMillis  = 0d;
                float  leftChannelWidth  = 0;
                float  rightChannelWidth = 0;

                if (e.EngineState.HasAudio)
                {
                    lock (drawVuMeterRmsLock)
                    {
                        differenceMillis  = Math.Round(TimeSpan.FromTicks(drawVuMeterClock.Ticks - e.StartTime.Ticks).TotalMilliseconds, 0);
                        leftChannelWidth  = drawVuMeterMinWidth + (Convert.ToSingle(drawVuMeterLeftValue) * drawVuMeterScaleFactor);
                        rightChannelWidth = drawVuMeterMinWidth + (Convert.ToSingle(drawVuMeterRightValue) * drawVuMeterScaleFactor);
                    }
                }

                overlayGraphics.DrawString($"Clock: {e.Clock.TotalSeconds:00.00}\r\nPN   : {e.PictureNumber}\r\nA/V  : {differenceMillis:+000;-000}\r\nL \r\nR",
                                           overlayTextFont,
                                           overlayTextFontBrush,
                                           overlayTextOffset);

                // draw a simple VU meter
                overlayGraphics.DrawLine(drawVuMeterLeftPen,
                                         drawVuMeterLeftOffset,
                                         drawVuMeterTopOffset * overlayGraphics.DpiY / 96f,
                                         drawVuMeterLeftOffset + leftChannelWidth,
                                         drawVuMeterTopOffset * overlayGraphics.DpiY / 96f);

                overlayGraphics.DrawLine(drawVuMeterRightPen,
                                         drawVuMeterLeftOffset,
                                         (drawVuMeterTopOffset + drawVuMeterTopSpacing) * overlayGraphics.DpiY / 96f,
                                         drawVuMeterLeftOffset + rightChannelWidth,
                                         (drawVuMeterTopOffset + drawVuMeterTopSpacing) * overlayGraphics.DpiY / 96f);

                #endregion
            };

            Media.RenderingAudio += (s, e) =>
            {
                // If we don't have video, we don't need to draw a thing.
                if (e.EngineState.HasVideo == false)
                {
                    return;
                }

                // We need to split the samples into left and right sample channels
                if (drawVuMeterLeftSamples == null || drawVuMeterLeftSamples.Length != e.SamplesPerChannel)
                {
                    drawVuMeterLeftSamples = new double[e.SamplesPerChannel];
                }

                if (rdrawVuMeterRightSamples == null || rdrawVuMeterRightSamples.Length != e.SamplesPerChannel)
                {
                    rdrawVuMeterRightSamples = new double[e.SamplesPerChannel];
                }

                // Iterate through the buffer
                var isLeftSample  = true;
                var sampleIndex   = 0;
                var samplePercent = default(double);

                for (var i = 0; i < e.BufferLength; i += e.BitsPerSample / 8)
                {
                    samplePercent = 100d * e.Buffer.GetAudioSampleLevel(i);

                    if (isLeftSample)
                    {
                        drawVuMeterLeftSamples[sampleIndex] = samplePercent;
                    }
                    else
                    {
                        rdrawVuMeterRightSamples[sampleIndex] = samplePercent;
                    }

                    sampleIndex += !isLeftSample ? 1 : 0;
                    isLeftSample = !isLeftSample;
                }

                // Compute the RMS of the samples and save it for the given point in time.
                lock (drawVuMeterRmsLock)
                {
                    // The VU meter should show the audio RMS, we compute it and save it in a dictionary.
                    drawVuMeterClock      = TimeSpan.FromTicks(e.StartTime.Ticks + (e.Duration.Ticks / 2));
                    drawVuMeterLeftValue  = Math.Sqrt((1d / drawVuMeterLeftSamples.Length) * drawVuMeterLeftSamples.Sum(n => n));
                    drawVuMeterRightValue = Math.Sqrt((1d / rdrawVuMeterRightSamples.Length) * rdrawVuMeterRightSamples.Sum(n => n));
                }
            };

            Media.RenderingSubtitles += (s, e) =>
            {
                // a simple example of suffixing subtitles
                // if (e.Text != null && e.Text.Count > 0 && e.Text[e.Text.Count - 1] != "(subtitles)")
                //    e.Text.Add("(subtitles)");
            };

            Media.AudioDeviceStopped += (s, e) =>
            {
                // If we detect that the audio device has stopped, simply
                // call the changemedia command so the default audio device gets selected
                // and reopened. See issue #93
                var task = Media.ChangeMedia();
            };

            #endregion
        }
Esempio n. 10
0
        /// <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)
        {
            //FileUpload fileUpload,
            //HttpPostedFile hpf = fileUpload.PostedFile;

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            //System.Drawing.Image originalImage = System.Drawing.Image.FromStream(hpf.InputStream, true);

            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();
            }
        }
Esempio n. 11
0
        //return "0" for single face and "c"(cache) for multiple face
        //for multiple face, the face rectangles are stored in CCommon.cacheRects
        //CComon.cacheBm store the 24bit Bitmap for source image
        public static string FindFaceAndEyes(BitmapSource srcimage, out System.Drawing.Rectangle facerect, out System.Drawing.Rectangle[] eyesrect)
        {
            String faceFileName = AppDomain.CurrentDomain.BaseDirectory + "haarcascade_frontalface_alt2.xml";
            String eyeFileName  = AppDomain.CurrentDomain.BaseDirectory + "haarcascade_eye.xml";

            //working with gdi to get 24bit rgb image
            System.Drawing.Bitmap   bmtest   = CCommon.BitmapImage2Bitmap(srcimage);
            System.Drawing.Bitmap   bmsrc24  = new System.Drawing.Bitmap(bmtest.Width, bmtest.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            System.Drawing.Graphics gbmsrc24 = System.Drawing.Graphics.FromImage(bmsrc24);
            gbmsrc24.DrawImageUnscaled(bmtest, 0, 0);
            gbmsrc24.Dispose();
            bmtest.Dispose();
            bmtest = null;

            if (cacheBm != null)
            {
                cacheBm.Dispose();
            }
            cacheBm = (System.Drawing.Bitmap)bmsrc24.Clone();

            //we do scaling if the source is too large
            double scale = 1.0;

            if (bmsrc24.Height > 500)
            {
                scale = (double)500 / bmsrc24.Height;
            }

            System.Drawing.Bitmap bm = new System.Drawing.Bitmap((int)(bmsrc24.Width * scale),
                                                                 (int)(bmsrc24.Height * scale),
                                                                 System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            System.Drawing.Graphics gbm = System.Drawing.Graphics.FromImage(bm);

            //scale down the source image for face dection
            gbm.DrawImage(bmsrc24,
                          new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height),
                          new System.Drawing.Rectangle(0, 0, bmsrc24.Width, bmsrc24.Height),
                          System.Drawing.GraphicsUnit.Pixel);
            gbm.Dispose();

            // bm.Save(AppDomain.CurrentDomain.BaseDirectory +"temp\\~bm.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
            //////////////////////////////////////////


            IntelImage _img = CDetectFace.CreateIntelImageFromBitmap(bm);

            //IntPtr p_face = CDetectFace.HistEqualize(_img);
            bm.Dispose();
            bm = null;
            string strindex = "";

            using (HaarClassifier haarface = new HaarClassifier(faceFileName))
                using (HaarClassifier haareye = new HaarClassifier(eyeFileName))
                {
                    var faces = haarface.DetectObjects(_img.IplImage());
                    // var faces = haarface.DetectObjects(p_face );
                    if (faces.Count > 0)
                    {
                        List <System.Drawing.Rectangle> facerects = new List <System.Drawing.Rectangle>();
                        for (int i = 0; i < faces.Count; i++)
                        {
                            var face = faces.ElementAt(i);
                            System.Drawing.Rectangle rt = new System.Drawing.Rectangle((int)(face.x / scale),
                                                                                       (int)(face.y / scale),
                                                                                       (int)(face.width / scale),
                                                                                       (int)(face.height / scale));
                            facerects.Add(rt);
                        }
                        cacheRects = facerects;

                        if (faces.Count > 1)
                        {
                            //clean up and return
                            eyesrect = null;
                            facerect = facerect = System.Drawing.Rectangle.Empty;

                            _img.Dispose();
                            bmsrc24.Dispose();
                            bmsrc24 = null;

                            return("c"); //cached
                        }
                    }
                    else
                    {
                        cacheRects.Clear();
                    }

                    //only handle 1 face
                    if (faces.Count == 1)
                    {
                        var face = faces.ElementAt(0);

                        facerect = new System.Drawing.Rectangle((int)(face.x / scale),
                                                                (int)(face.y / scale),
                                                                (int)(face.width / scale),
                                                                (int)(face.height / scale));

                        int x = facerect.X, y = facerect.Y, h0 = facerect.Height, w0 = facerect.Width;

                        //to handle oversize face area
                        double rescale = 1.0;
                        if (h0 > 300)
                        {
                            rescale = 300.0 / h0;
                        }

                        System.Drawing.Rectangle temprect = new System.Drawing.Rectangle(x, y, w0, 10 * h0 / 16);

                        System.Drawing.Bitmap bm_eyes = bmsrc24.cropAtRect(temprect);

                        bm_eyes.Save(AppDomain.CurrentDomain.BaseDirectory + "temp\\~eye.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                        IntelImage image_eyes = CDetectFace.CreateIntelImageFromBitmap(bm_eyes);

                        //resize eyes area for better detection
                        IntelImage image_eyes2X = new IntelImage((int)(image_eyes.IplImageStruc().width *2 * rescale),
                                                                 (int)(image_eyes.IplImageStruc().height *2 * rescale));
                        NativeMethods.CvResize(image_eyes.IplImage(), image_eyes2X.IplImage(), NativeMethods.CV_INTER_CUBIC);

                        IntPtr p_eq_img_eyes = CDetectFace.HistEqualize(image_eyes2X);

                        var eyes = haareye.DetectObjects(p_eq_img_eyes);

                        ////clean up
                        NativeMethods.cvReleaseImage(ref p_eq_img_eyes);
                        image_eyes.Dispose();
                        image_eyes = null;
                        bm_eyes.Dispose();

                        image_eyes2X.Dispose();
                        image_eyes2X = null;

                        if (eyes.Count > 0)
                        {
                            eyesrect = new System.Drawing.Rectangle[eyes.Count];

                            for (int i = 0; i < eyesrect.Length; i++)
                            {
                                var eye = eyes.ElementAt(i);

                                //note that we had scale the eyes area by 2, so we scale back
                                eyesrect[i] = new System.Drawing.Rectangle((int)(eye.x / (2 * rescale)),
                                                                           (int)(eye.y / (2 * rescale)),
                                                                           (int)(eye.width / (2 * rescale)),
                                                                           (int)(eye.height / (2 * rescale)));
                            }


                            int mineyesize = (h0 / 12);
                            int maxeyesize = (h0 / 3);
                            //sorting
                            var tempeyeslist = eyesrect.ToList();


                            //dist to center of face
                            //  <-1/2 w -->
                            //  |          |          |
                            //  |<-x ->o<d>|          |
                            //  |          |          |
                            //  |          |          |
                            //  |          |          |
                            // o=center of eye
                            // x= x dist to center of eye
                            // d= difference of 1/2 w and x
                            //  = distance of eye center to center of face
                            // the further this distance, the more likely it is an eye
                            int half_facewidth = facerect.Width / 2;
                            tempeyeslist = tempeyeslist.OrderByDescending(eye => Math.Abs(eye.X + eye.Width / 2 - (half_facewidth))).ToList();

                            //size: should be within min and max eye size
                            tempeyeslist = tempeyeslist.OrderByDescending(eye => (eye.Width > mineyesize)).ToList();
                            tempeyeslist = tempeyeslist.OrderByDescending(eye => (eye.Width < maxeyesize)).ToList();


                            eyesrect = tempeyeslist.ToArray();
                        }
                        else
                        {
                            eyesrect = null;
                        }
                    }
                    else
                    {
                        facerect = System.Drawing.Rectangle.Empty;
                        eyesrect = null;
                    }
                }

            //NativeMethods.cvReleaseImage(ref  p_face );

            _img.Dispose();

            bmsrc24.Dispose();
            bmsrc24 = null;

            return(strindex);
        }
Esempio n. 12
0
        // ====================================================================
        // Creates the bitmap image.
        // ====================================================================
        private void GenerateImage()
        {
            // Create a new 32-bit bitmap image.
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(this.width, this.height
                                                                     , System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, this.width, this.height);

            // Fill in the background.
            System.Drawing.Drawing2D.HatchBrush hatchBrush =
                new System.Drawing.Drawing2D.HatchBrush(
                    System.Drawing.Drawing2D.HatchStyle.SmallConfetti
                    , System.Drawing.Color.LightGray
                    , System.Drawing.Color.White);
            g.FillRectangle(hatchBrush, rect);

            // Set up the text font.
            System.Drawing.SizeF size;
            float fontSize = rect.Height + 1;

            System.Drawing.Font font;
            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize--;
                font = new System.Drawing.Font(this.familyName, fontSize, System.Drawing.FontStyle.Bold);
                size = g.MeasureString(this.text, font);
            } while (size.Width > rect.Width);

            // Set up the text format.
            System.Drawing.StringFormat format = new System.Drawing.StringFormat();
            format.Alignment     = System.Drawing.StringAlignment.Center;
            format.LineAlignment = System.Drawing.StringAlignment.Center;

            // Create a path using the text and warp it randomly.
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
            float v = 4F;

            System.Drawing.PointF[] points =
            {
                new System.Drawing.PointF(this.random.Next(rect.Width) / v,              this.random.Next(rect.Height) / v),
                new System.Drawing.PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                new System.Drawing.PointF(this.random.Next(rect.Width) / v,              rect.Height - this.random.Next(rect.Height) / v),
                new System.Drawing.PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
            };
            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.Translate(0F, 0F);
            path.Warp(points, rect, matrix, System.Drawing.Drawing2D.WarpMode.Perspective, 0F);

            // Draw the text.
            hatchBrush = new System.Drawing.Drawing2D.HatchBrush(
                System.Drawing.Drawing2D.HatchStyle.LargeConfetti
                , System.Drawing.Color.LightGray
                , System.Drawing.Color.DarkGray);
            g.FillPath(hatchBrush, path);

            // Add some random noise.
            int m = System.Math.Max(rect.Width, rect.Height);

            for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
            {
                int x = this.random.Next(rect.Width);
                int y = this.random.Next(rect.Height);
                int w = this.random.Next(m / 50);
                int h = this.random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }

            // Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

            // Set the image.
            this.image = bitmap;
        }
        private void DrawHorizontalRuler()
        {
            if (this.bmp == null)
            {
                int width = this.ActualWidth < 0.1 ? 3 : (int)this.Width;

                int height = this.ActualHeight < 0.1 ? 3 : (int)this.Height;

                if (width <= 0)
                {
                    width = 1;
                }

                if (height <= 0)
                {
                    height = 1;
                }

                this.bmp = new System.Drawing.Bitmap(width, height);

                System.Drawing.Graphics grap = System.Drawing.Graphics.FromImage(bmp);

                try
                {
                    double cmVal = DistanceConverter.ConvertPixelToCm(this.Width);

                    double iSmall = Math.Abs(DistanceConverter.ConvertCmToPixel(0.1));

                    grap.FillRectangle(System.Drawing.Brushes.WhiteSmoke, 0, 0, this.bmp.Width, bmp.Height);

                    for (int x = 0; x < cmVal; x++)
                    {
                        int iX = Convert.ToInt32(Math.Abs(DistanceConverter.ConvertCmToPixel(x)));

                        double iStart = Math.Abs(DistanceConverter.ConvertCmToPixel(x)) + iSmall;

                        double iEnd = Math.Abs(DistanceConverter.ConvertCmToPixel(x + 1));

                        int midCount = 1;

                        this.DrawRulerLine(grap, iX, iX, 15, 0);

                        if (x > 0)
                        {
                            this.DrawRulerNumber(grap, x, iX);
                        }

                        while (Convert.ToInt32(iStart) < Convert.ToInt32(iEnd))
                        {
                            int iS = Convert.ToInt32(iStart);

                            this.DrawRulerLine(grap, iS, iS, midCount == 5 ? 10 : 6, 0);

                            iStart += iSmall;

                            midCount++;
                        }
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    grap.Dispose();
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <param name="checkCode"></param>
        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 < 4; 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();
            }
        }
Esempio n. 15
0
        protected void buttonCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            PdfDocument document = new PdfDocument();

            // set a demo serial number
            document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // create a page in document
            PdfPage page1 = document.AddPage();

            // create the true type fonts that can be used in document text
            System.Drawing.Font sysFont      = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point);
            PdfFont             pdfFont      = document.CreateFont(sysFont);
            PdfFont             pdfFontEmbed = document.CreateFont(sysFont, true);

            System.Drawing.Font sysFontBold = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold,
                                                                      System.Drawing.GraphicsUnit.Point);
            PdfFont pdfFontBold      = document.CreateFont(sysFontBold);
            PdfFont pdfFontBoldEmbed = document.CreateFont(sysFontBold, true);

            // create a standard Helvetica Type 1 font that can be used in document text
            PdfFont helveticaStdFont = document.CreateStandardFont(PdfStandardFont.Helvetica);

            helveticaStdFont.Size = 10;

            float crtYPos = 20;
            float crtXPos = 5;

            PdfLayoutInfo textLayoutInfo = null;

            string dummyText = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

            #region Layout a text that expands to the right edge of the PDF page

            PdfText titleTextAtLocation = new PdfText(crtXPos, crtYPos,
                                                      "The text below extends from the layout position to the right edge of the PDF page:", pdfFontBoldEmbed);
            titleTextAtLocation.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextAtLocation);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            PdfText textExpandsToRightEdge = new PdfText(crtXPos + 50, crtYPos, dummyText, pdfFont);
            textExpandsToRightEdge.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textExpandsToRightEdge);

            // draw a rectangle around the text
            PdfRectangle borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            #endregion

            #region Layout a text with width limit

            PdfText titleTextWithWidth = new PdfText(crtXPos, crtYPos,
                                                     "The text below is limited by a given width and has a free height:", pdfFontBoldEmbed);
            titleTextWithWidth.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextWithWidth);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            PdfText textWithWidthLimit = new PdfText(crtXPos + 50, crtYPos, 300, dummyText, pdfFont);
            textWithWidthLimit.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textWithWidthLimit);

            // draw a rectangle around the text
            borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            #endregion

            #region Layout a text with width and height limits

            PdfText titleTextWithWidthAndHeight = new PdfText(crtXPos, crtYPos,
                                                              "The text below is limited by a given width and height and is trimmed:", pdfFontBoldEmbed);
            titleTextWithWidthAndHeight.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextWithWidthAndHeight);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            PdfText textWithWidthAndHeightLimit = new PdfText(crtXPos + 50, crtYPos, 300, 50, dummyText, pdfFont);
            textWithWidthAndHeightLimit.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textWithWidthAndHeightLimit);

            // draw a rectangle around the text
            borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            #endregion

            #region Layout a text with standard font

            PdfText textWithStandardFont = new PdfText(crtXPos, crtYPos, "This green text is written with a Helvetica Standard Type 1 font", helveticaStdFont);
            textWithStandardFont.BackColor = System.Drawing.Color.WhiteSmoke;
            textWithStandardFont.ForeColor = System.Drawing.Color.Green;
            textLayoutInfo = page1.Layout(textWithStandardFont);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            #endregion

            #region Layout a rotated text

            PdfText titleRotatedText = new PdfText(crtXPos, crtYPos, "The text below is rotated:", pdfFontBoldEmbed);
            titleRotatedText.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo             = page1.Layout(titleRotatedText);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            // create a reference Graphics used for measuring
            System.Drawing.Bitmap   refBmp      = new System.Drawing.Bitmap(1, 1);
            System.Drawing.Graphics refGraphics = System.Drawing.Graphics.FromImage(refBmp);
            refGraphics.PageUnit = System.Drawing.GraphicsUnit.Point;

            string counterRotatedText = "This text is rotated 45 degrees counter clockwise";

            // measure the rotated text size
            System.Drawing.SizeF counterRotatedTextSize = refGraphics.MeasureString(counterRotatedText, sysFont);

            // advance the Y position in the PDF page
            crtYPos += counterRotatedTextSize.Width / (float)Math.Sqrt(2) + 10;

            string clockwiseRotatedText = "This text is rotated 45 degrees clockwise";

            PdfText rotatedCounterClockwiseText = new PdfText(crtXPos + 100, crtYPos, counterRotatedText, pdfFontEmbed);
            rotatedCounterClockwiseText.RotationAngle = 45;
            textLayoutInfo = page1.Layout(rotatedCounterClockwiseText);

            PdfText rotatedClockwiseText = new PdfText(crtXPos + 100, crtYPos, clockwiseRotatedText, pdfFontEmbed);
            rotatedClockwiseText.RotationAngle = -45;
            textLayoutInfo = page1.Layout(rotatedClockwiseText);

            // measure the rotated text size
            System.Drawing.SizeF clockwiseRotatedTextSize = refGraphics.MeasureString(clockwiseRotatedText, sysFont);

            // advance the Y position in the PDF page
            crtYPos += clockwiseRotatedTextSize.Width / (float)Math.Sqrt(2) + 10;

            // dispose the graphics used for measuring
            refGraphics.Dispose();
            refBmp.Dispose();

            #endregion

            #region Layout an automatically paginated text

            string dummyBigText = System.IO.File.ReadAllText(Server.MapPath("~") + @"\DemoFiles\Text\DummyBigText.txt");

            PdfText titleTextPaginated = new PdfText(crtXPos, crtYPos,
                                                     "The text below is automatically paginated when it gets to the bottom of this page:", pdfFontBoldEmbed);
            titleTextPaginated.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextPaginated);

            // advance the Y position in the PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            PdfText paginatedText = new PdfText(crtXPos + 50, crtYPos, 300, dummyBigText, pdfFont);
            paginatedText.BackColor = System.Drawing.Color.WhiteSmoke;
            paginatedText.Cropping  = false;
            textLayoutInfo          = page1.Layout(paginatedText);

            // get the last page where the text was rendered
            PdfPage crtPage = document.Pages[textLayoutInfo.LastPageIndex];

            // draw a line at the bottom of the text on the second page
            System.Drawing.PointF leftPoint  = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Left, textLayoutInfo.LastPageRectangle.Bottom);
            System.Drawing.PointF rightPoint = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Right, textLayoutInfo.LastPageRectangle.Bottom);
            PdfLine borderLine = new PdfLine(leftPoint, rightPoint);
            borderLine.LineStyle.LineWidth = 0.5f;
            crtPage.Layout(borderLine);

            // advance the Y position in the second PDF page
            crtYPos += textLayoutInfo.LastPageRectangle.Height + 10;

            #endregion

            try
            {
                // write the PDF document to a memory buffer
                byte[] pdfBuffer = document.WriteToMemory();

                // inform the browser about the binary data format
                HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");

                // let the browser know how to open the PDF document and the file name
                HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfText.pdf; size={0}",
                                                                                            pdfBuffer.Length.ToString()));

                // write the PDF buffer to HTTP response
                HttpContext.Current.Response.BinaryWrite(pdfBuffer);

                // call End() method of HTTP response to stop ASP.NET page processing
                HttpContext.Current.Response.End();
            }
            finally
            {
                document.Close();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// 缩放图像
        /// </summary>
        /// <param name="originalImagePath">图片原始路径</param>
        /// <param name="thumNailPath">保存路径</param>
        /// <param name="width">缩放图的宽</param>
        /// <param name="height">缩放图的高</param>
        /// <param name="model">缩放模式</param>
        public static void MakeThumNail(string originalImagePath, string thumNailPath, int width, int height, string model)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int thumWidth  = width;     //缩略图的宽度
            int thumHeight = height;    //缩略图的高度

            int x = 0;
            int y = 0;

            int originalWidth  = originalImage.Width;   //原始图片的宽度
            int originalHeight = originalImage.Height;  //原始图片的高度

            switch (model)
            {
            case "HW":          //指定高宽缩放,可能变形
                break;

            case "W":           //指定宽度,高度按照比例缩放
                thumHeight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":           //指定高度,宽度按照等比例缩放
                thumWidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":
                if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                {
                    originalHeight = originalImage.Height;
                    originalWidth  = originalImage.Height * thumWidth / thumHeight;
                    y = 0;
                    x = (originalImage.Width - originalWidth) / 2;
                }
                else
                {
                    originalWidth  = originalImage.Width;
                    originalHeight = originalWidth * height / thumWidth;
                    x = 0;
                    y = (originalImage.Height - originalHeight) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);

            //新建一个画板
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量查值法
            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            graphic.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                bitmap.Save(thumNailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                graphic.Dispose();
                File.Delete(originalImagePath);
            }
        }
Esempio n. 17
0
        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);
                int width  = original_image.Width;
                int height = original_image.Height;
                final_image = new System.Drawing.Bitmap(original_image);
                graphic     = System.Drawing.Graphics.FromImage(final_image);
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphic.DrawImage(original_image, 0, 0, width, height);
                ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                string           thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                Thumbnail        thumb        = new Thumbnail(thumbnail_id, ms.GetBuffer());
                List <Thumbnail> thumbnails   = Session["file_info"] as List <Thumbnail>;
                if (thumbnails == null)
                {
                    thumbnails           = new List <Thumbnail>();
                    Session["file_info"] = thumbnails;
                }
                thumbnails.Add(thumb);

                Response.StatusCode = 200;
                Response.Write(thumbnail_id);
            }
            catch (Exception ex)
            {
                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 (ms != null)
                {
                    ms.Close();
                }
                Response.End();
            }
        }
Esempio n. 18
0
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置:0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param>

        public static void AddImageSignPic(string Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            System.Drawing.Image    img = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);

            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            System.Drawing.Imaging.ColorMap        colorMap        = new System.Drawing.Imaging.ColorMap();

            colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);

            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo   ici    = null;
            foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
            {
                //if (codec.MimeType.IndexOf("jpeg") > -1)
                if (codec.MimeType.Contains("jpeg"))
                {
                    ici = codec;
                }
            }
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            qualityParam[0] = quality;

            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Esempio n. 19
0
        private string CreateImage()
        {
            string thumbnail_id = string.Empty;

            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 {
                HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

                original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);

                int new_width     = original_image.Width;
                int new_height    = original_image.Height;
                int target_width  = new_width;
                int target_height = new_height;

                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(original_image, paste_x, paste_y, new_width, new_height);
                ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer());

                List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>;
                if (thumbnails == null)
                {
                    thumbnails = new List <Thumbnail>();
                    HttpContext.Current.Session["file_info"] = thumbnails;
                }
                thumbnails.Add(thumb);
            }
            catch {
                return(string.Empty);
            }
            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();
                }
            }

            return(thumbnail_id);
        }
        /// <summary>
        /// Provides examples for rendering events
        /// </summary>
        private void BindRenderingEvents()
        {
            #region Audio and Video Frame Rendering Variables

#if !HANDLE_RENDERING_EVENTS
            return;
#endif

            // We can extract the closed caption data into a file if we need to.
            var closedCaptionsFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "608.bin");
            var saveClosedCaptions = false;

            // Setup GDI+ graphics
            System.Drawing.Bitmap   overlayBitmap   = null;
            System.Drawing.Graphics overlayGraphics = null;
            var overlayTextFont      = new System.Drawing.Font("Arial", 14, System.Drawing.FontStyle.Bold);
            var overlayTextFontBrush = System.Drawing.Brushes.WhiteSmoke;
            var overlayTextOffset    = new System.Drawing.PointF(12, 8);
            var overlayBackBuffer    = IntPtr.Zero;

            var drawVuMeterLeftPen  = new System.Drawing.Pen(System.Drawing.Color.OrangeRed, 12);
            var drawVuMeterRightPen = new System.Drawing.Pen(System.Drawing.Color.GreenYellow, 12);
            var drawVuMeterRmsLock  = new object();
            var drawVuMeterLeftRms  = new SortedDictionary <TimeSpan, double>();
            var drawVuMeterRightRms = new SortedDictionary <TimeSpan, double>();

            var         drawVuMeterLeftValue   = 0d;
            var         drawVuMeterRightValue  = 0d;
            const float drawVuMeterLeftOffset  = 16;
            const float drawVuMeterTopOffset   = 50;
            const float drawVuMeterScaleFactor = 20; // RMS * pixel factor = the length of the VU meter lines

            #endregion

            #region Rendering Event Examples

            Media.RenderingVideo += (s, e) =>
            {
                if (saveClosedCaptions && e.ClosedCaptions.All.Count > 0)
                {
                    var byteList = new List <byte>(4096);
                    byteList.AddRange(BitConverter.GetBytes(e.StartTime.Ticks));
                    byteList.AddRange(BitConverter.GetBytes(e.ClosedCaptions.All.Count * 3));
                    foreach (var cc in e.ClosedCaptions.All)
                    {
                        byteList.AddRange(cc.Data);
                    }

                    using (var stream = new FileStream(closedCaptionsFile, FileMode.Append))
                    {
                        stream.Write(byteList.ToArray(), 0, byteList.Count);
                    }
                }

                #region Create the overlay buffer to work with

                if (overlayBackBuffer != e.Bitmap.Scan0)
                {
                    lock (drawVuMeterRmsLock)
                    {
                        drawVuMeterLeftRms.Clear();
                        drawVuMeterRightRms.Clear();
                    }

                    if (overlayGraphics != null)
                    {
                        overlayGraphics.Dispose();
                    }
                    if (overlayBitmap != null)
                    {
                        overlayBitmap.Dispose();
                    }

                    overlayBitmap = e.Bitmap.CreateDrawingBitmap();

                    overlayBackBuffer = e.Bitmap.Scan0;
                    overlayGraphics   = System.Drawing.Graphics.FromImage(overlayBitmap);
                    overlayGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                }

                #endregion

                #region Read the instantaneous RMS of the audio

                lock (drawVuMeterRmsLock)
                {
                    var position = e.Clock;
                    drawVuMeterLeftValue  = drawVuMeterLeftRms.Where(kvp => kvp.Key > position).Select(kvp => kvp.Value).FirstOrDefault();
                    drawVuMeterRightValue = drawVuMeterRightRms.Where(kvp => kvp.Key > position).Select(kvp => kvp.Value).FirstOrDefault();

                    // do some cleanup so the dictionary does not grow too big.
                    if (drawVuMeterLeftRms.Count > 256)
                    {
                        var keysToRemove = drawVuMeterLeftRms.Keys.Where(k => k < position).OrderBy(k => k).ToArray();
                        foreach (var k in keysToRemove)
                        {
                            drawVuMeterLeftRms.Remove(k);
                            drawVuMeterRightRms.Remove(k);

                            if (drawVuMeterLeftRms.Count < 256)
                            {
                                break;
                            }
                        }
                    }
                }

                #endregion

                #region Draw the text and the VU meter

                var differenceMillis = TimeSpan.FromTicks(e.Clock.Ticks - e.StartTime.Ticks).TotalMilliseconds;

                overlayGraphics.DrawString($"Clock: {e.StartTime.TotalSeconds:00.000} | Skew: {differenceMillis:00.000} | PN: {e.PictureNumber}",
                                           overlayTextFont,
                                           overlayTextFontBrush,
                                           overlayTextOffset);

                // draw a simple VU meter
                overlayGraphics.DrawLine(drawVuMeterLeftPen,
                                         drawVuMeterLeftOffset,
                                         drawVuMeterTopOffset,
                                         drawVuMeterLeftOffset + 5 + (Convert.ToSingle(drawVuMeterLeftValue) * drawVuMeterScaleFactor),
                                         drawVuMeterTopOffset);

                overlayGraphics.DrawLine(drawVuMeterRightPen,
                                         drawVuMeterLeftOffset,
                                         drawVuMeterTopOffset + 20,
                                         drawVuMeterLeftOffset + 5 + (Convert.ToSingle(drawVuMeterRightValue) * drawVuMeterScaleFactor),
                                         drawVuMeterTopOffset + 20);

                #endregion
            };

            Media.RenderingAudio += (s, e) =>
            {
                // The buffer contains all the samples
                var buffer = new byte[e.BufferLength];
                Marshal.Copy(e.Buffer, buffer, 0, e.BufferLength);

                // We need to split the samples into left and right samples
                var leftSamples  = new double[e.SamplesPerChannel];
                var rightSamples = new double[e.SamplesPerChannel];

                // Iterate through the buffer
                var isLeftSample  = true;
                var sampleIndex   = 0;
                var samplePercent = default(double);

                for (var i = 0; i < e.BufferLength; i += e.BitsPerSample / 8)
                {
                    samplePercent = 100d * buffer.GetAudioSampleLevel(i);

                    if (isLeftSample)
                    {
                        leftSamples[sampleIndex] = samplePercent;
                    }
                    else
                    {
                        rightSamples[sampleIndex] = samplePercent;
                    }

                    sampleIndex += !isLeftSample ? 1 : 0;
                    isLeftSample = !isLeftSample;
                }

                // Compute the RMS of the samples and save it for the given point in time.
                lock (drawVuMeterRmsLock)
                {
                    // The VU meter should show the audio RMS, we compute it and save it in a dictionary.
                    drawVuMeterLeftRms[e.StartTime]  = Math.Sqrt((1d / leftSamples.Length) * leftSamples.Sum(n => n));
                    drawVuMeterRightRms[e.StartTime] = Math.Sqrt((1d / rightSamples.Length) * rightSamples.Sum(n => n));
                }
            };

            Media.RenderingSubtitles += (s, e) =>
            {
                // a simple example of suffixing subtitles
                // if (e.Text != null && e.Text.Count > 0 && e.Text[e.Text.Count - 1] != "(subtitles)")
                //    e.Text.Add("(subtitles)");
            };

            #endregion
        }
Esempio n. 21
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="Content">内容文本</param>
        /// <param name="QRCodeEncodeMode">二维码编码方式</param>
        /// <param name="QRCodeErrorCorrect">纠错码等级</param>
        /// <param name="QRCodeVersion">二维码版本号 0-40</param>
        /// <param name="QRCodeScale">每个小方格的预设宽度(像素),正整数</param>
        /// <param name="size">图片尺寸(像素),0表示不设置</param>
        /// <param name="border">图片白边(像素),当size大于0时有效</param>
        /// <returns></returns>
        public System.Drawing.Image CreateQRCode(string Content, QRCodeEncoder.ENCODE_MODE QRCodeEncodeMode, QRCodeEncoder.ERROR_CORRECTION QRCodeErrorCorrect, int QRCodeVersion, int QRCodeScale, int size, int border)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

            qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncodeMode;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeErrorCorrect;
            qrCodeEncoder.QRCodeScale        = QRCodeScale;
            qrCodeEncoder.QRCodeVersion      = QRCodeVersion;
            System.Drawing.Image image = qrCodeEncoder.Encode(Content);

            #region 根据设定的目标图片尺寸调整二维码QRCodeScale设置,并添加边框
            if (size > 0)
            {
                //当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸
                #region 当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸
                while (image.Width < size)
                {
                    qrCodeEncoder.QRCodeScale++;
                    System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                    if (imageNew.Width < size)
                    {
                        image = new System.Drawing.Bitmap(imageNew);
                        imageNew.Dispose();
                        imageNew = null;
                    }
                    else
                    {
                        qrCodeEncoder.QRCodeScale--; //新尺寸未采用,恢复最终使用的尺寸
                        imageNew.Dispose();
                        imageNew = null;
                        break;
                    }
                }
                #endregion

                //当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸
                #region 当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸
                while (image.Width > size && qrCodeEncoder.QRCodeScale > 1)
                {
                    qrCodeEncoder.QRCodeScale--;
                    System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                    image = new System.Drawing.Bitmap(imageNew);
                    imageNew.Dispose();
                    imageNew = null;
                    if (image.Width < size)
                    {
                        break;
                    }
                }
                #endregion

                //如果目标尺寸大于生成的图片尺寸,则为图片增加白边
                #region 如果目标尺寸大于生成的图片尺寸,则为图片增加白边
                if (image.Width <= size)
                {
                    //根据参数设置二维码图片白边的最小宽度
                    #region 根据参数设置二维码图片白边的最小宽度
                    if (border > 0)
                    {
                        while (image.Width <= size && size - image.Width < border * 2 && qrCodeEncoder.QRCodeScale > 1)
                        {
                            qrCodeEncoder.QRCodeScale--;
                            System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content);
                            image = new System.Drawing.Bitmap(imageNew);
                            imageNew.Dispose();
                            imageNew = null;
                        }
                    }
                    #endregion

                    //当目标图片尺寸大于二维码尺寸时,将二维码绘制在目标尺寸白色画布的中心位置
                    if (image.Width < size)
                    {
                        //新建空白绘图
                        System.Drawing.Bitmap   panel    = new System.Drawing.Bitmap(size, size);
                        System.Drawing.Graphics graphic0 = System.Drawing.Graphics.FromImage(panel);
                        int p_left = 0;
                        int p_top  = 0;
                        if (image.Width <= size) //如果原图比目标形状宽
                        {
                            p_left = (size - image.Width) / 2;
                        }
                        if (image.Height <= size)
                        {
                            p_top = (size - image.Height) / 2;
                        }

                        //将生成的二维码图像粘贴至绘图的中心位置
                        graphic0.DrawImage(image, p_left, p_top, image.Width, image.Height);
                        image = new System.Drawing.Bitmap(panel);
                        panel.Dispose();
                        panel = null;
                        graphic0.Dispose();
                        graphic0 = null;
                    }
                }
                #endregion
            }
            #endregion
            return(image);
        }
Esempio n. 22
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">原图片路径</param>
        /// <param name="thumbnailPath">缩略图保存路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        public bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
        {
            bool isSucced = false;

            //获取原始图片
            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;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量
            double multiple = 0;

            //获取宽长的或是高长与缩略图的倍数
            if (originalImage.Width >= originalImage.Height)
            {
                multiple = (double)originalImage.Width / (double)width;
            }
            else
            {
                multiple = (double)originalImage.Height / (double)height;
            }
            //上传的图片的宽和高小等于缩略图
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图
            else
            {
                //宽高按比例缩放
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个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.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#F2F2F2"));
            //在指定位置并且按指定大小绘制原图片的指定部分
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //获取图片类型
                string fileExtension = System.IO.Path.GetExtension(originalImagePath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
                switch (fileExtension)
                {
                case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;

                case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;

                case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;

                case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                }

                isSucced = true;
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

            return(isSucced);
        }
        public static void Main(string[] args)
        {
            try // last-resort try/catch block
            {
#if !DEBUG
                // unless debugging, handle all thread exceptions
                Application.ThreadException += Application_ThreadException;
#endif

                // get language

                LangSettings lang = new LangSettings();
                lang.LoadFromRegistry();

                string langLogError = null, langLogEntry = null;
                uiCulture = Thread.CurrentThread.CurrentUICulture;

                try
                {
                    uiCulture = new CultureInfo(lang.langCode);
                    Thread.CurrentThread.CurrentUICulture = uiCulture;
                    langLogEntry = String.Format("Setting language to {0}", uiCulture.EnglishName);
                }
                catch (Exception ex)
                {
                    langLogError = String.Format("Failed to set language: {0}", ex.Message);
                }


                // get app version info

                version       = Assembly.GetExecutingAssembly().GetName().Version;
                versionString = Misc.VersionToString(version);


                // require win2k or greater, due to:
                // - GetLastInputInfo
                // - CredUIConfirmCredentials

                if (Environment.OSVersion.Version.Major < 5)
                {
                    MessageBox.Show(Language.Error_WindowsVersion,
                                    Language.Error_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                // perform basic dupe process detection
#if !MAC
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
                {
                    // make sure we're not just waiting for ourself to exit after changing to/from sleep mode
                    Thread.Sleep(2000);

                    if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
                    {
                        MessageBox.Show(Language.Error_AlreadyRunning,
                                        Language.Error_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
#endif


                // process command-line arguments

                bool argSleep = false;
                if (args.Length >= 1 && args[0] == "sleep")
                {
                    argSleep = true;
                }

                bool argAutowakeup = false;
                if (argSleep && args.Length >= 2 && args[1] == "autowakeup")
                {
                    argAutowakeup = true;
                }

                bool argMinimised = false;
                if (args.Length >= 1 && args[0] == "minimised")
                {
                    argMinimised = true;
                }


                // init log to file (will append if changing sleep <=> running)

                Log.OnNewLogEntry += Log.WriteToFile("BEGameMonitor.log");

                if (langLogError != null)
                {
                    Log.AddError(langLogError);
                }
                else if (langLogEntry != null)
                {
                    Log.AddEntry(langLogEntry);
                }


                // make it pretty

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);


                // if sleep arg, do sleep mode instead

                if (argSleep)
                {
                    Log.AddEntry("In sleep mode (autowakeup {0})", argAutowakeup ? "on" : "off");
                    new SleepTrayIcon(argAutowakeup);
                    Application.Run();
                    return;
                }


                // create game status window

                gameStatus = new GameStatus();


                // manually hide tary icon on app exit (tends to hang around until mouseover sometimes?!?)

                Application.ApplicationExit += Application_ApplicationExit;


                // make sure windows set to default dpi for now (otherwise will draw everything screwy)
                // TODO: make dpi independant?

                System.Drawing.Graphics g = gameStatus.CreateGraphics();
                int screenDpi             = (int)g.DpiX;
                g.Dispose();

                if (screenDpi != 96)
                {
                    MessageBox.Show(String.Format(Language.Error_NonDefaultDPI, screenDpi),
                                    Language.Error_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    gameStatus.trayIcon.Visible = false;
                    return;
                }


                // trick to force handle creation before Show()ing the form (to allow Invoke() to be called)

                IntPtr handle = gameStatus.Handle;


                // start initialisation in background, show the gui if necessary, and start the message loop

                gameStatus.Init();

                if (gameStatus.options.Startup.startMinimised || argMinimised)
                {
                } // start minimised
                else
                {
                    gameStatus.ShowWindow();
                }

                Application.Run();
            }
#if DEBUG
            catch
            {
                throw;
            }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            for (int im = 0; im < listFiles.Length; im++)
            {
                table = new System.Drawing.Bitmap(1281, 1025);
                gfxTable = System.Drawing.Graphics.FromImage(table);
                canvas.Children.Clear();
                risCanvas();
                Directory.CreateDirectory(putSave + @"\Level" + int.Parse(textBoxLevel.Text));
                file = new StreamWriter(putSave + @"\Level" + int.Parse(textBoxLevel.Text) + @"\Level" + int.Parse(textBoxLevel.Text) + ".txt");

                int narisKvadratov = 0; //Колличество нарисованных квадратов
                for (int i = 0; i < hPole; i++)
                    for (int j = 0; j < wPole; j++)
                    {
                        if (pole[i, j] == 0)
                        {
                            narisKvadratov++;
                            risuem(i, j, narisKvadratov, listFiles[im]);
                        }
                    }
                gfxTable.Dispose();
                file.Close();

                //Сохраняем разметку
                table.Save(putSave + @"\Level" + textBoxLevel.Text + @"\razmetka.png", System.Drawing.Imaging.ImageFormat.Png);
                table.Dispose();
                table = new System.Drawing.Bitmap(listFiles[im]);
                table.Save(putSave + @"\Level" + textBoxLevel.Text + @"\success.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                table.Dispose();
                textBoxLevel.Text = (Int32.Parse(textBoxLevel.Text) + 1).ToString();

                // Вывести массив
                if (true)
                {
                    for (int i = 0; i < hPole; i++)
                    {
                        for (int j = 0; j < wPole; j++)
                        {
                            pole[i, j] = 0;
                        }
                    }
                }

            }
        }
Esempio n. 25
0
 private static int MakePic(string sourceImg, string toPath, int pW, int pH)
 {
     System.Drawing.Image    originalImage = null;
     System.Drawing.Image    bitmap        = null;
     System.Drawing.Graphics g             = null;
     try
     {
         originalImage = System.Drawing.Image.FromFile(sourceImg);
         int oW = originalImage.Width;  //原始图片宽
         int oH = originalImage.Height; //原始图片高
         int tW = oW;                   //最终显示到页面宽
         int tH = oH;                   //最终显示到页面高
         if (oW > pW)                   //如果原始宽度大于固定宽度
         {
             tW = pW;                   //最终的宽度等于固定的宽度
             tH = pW * oH / oW;         //最终的高度等于固定宽度乘以原始高度除以原始宽度
             if (tH > pH)
             {
                 tH = pH;
                 tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度
             }
         }
         else if (oW < pW)//如果原始宽度小于固定宽度
         {
             tW = oW;
             if (oH > pH)
             {
                 tH = pH;
                 tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度
             }
         }
         else//如果原始宽度等于固定宽度
         {
             if (oH > pH)
             {
                 tH = pH;
                 tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度
             }
             if (oH < pH)
             {
                 tH = oH;
                 tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度
             }
             if (oH == pH)
             {
                 tH = oH;
                 tW = oW;
             }
         }
         //新建一个bmp图片
         bitmap = new System.Drawing.Bitmap(tW, tH);
         //新建一个画板
         g = System.Drawing.Graphics.FromImage(bitmap);
         //设置高质量插值法
         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
         //设置高质量,低速度呈现平滑程度
         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, tW, tH),
                     new System.Drawing.Rectangle(0, 0, oW, oH),
                     System.Drawing.GraphicsUnit.Pixel);
         //以jpg格式保存缩略图
         bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Jpeg);
         return(1);
     }
     catch
     {
         throw;
     }
     finally
     {
         if (originalImage != null)
         {
             originalImage.Dispose();
         }
         if (bitmap != null)
         {
             bitmap.Dispose();
         }
         if (g != null)
         {
             g.Dispose();
         }
     }
 }