Exemplo n.º 1
0
        public static byte[] Encode(string str)
        {
            var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            var qrCode    = qrEncoder.Encode(str);

            var render = new GraphicsRenderer(new FixedModuleSize(3, QuietZoneModules.Zero));
            var ms     = new MemoryStream();
            //render.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);


            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);

            int logosize = 20;

            using (Image img = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"Images\innerWhite-logo.png"))
            {
                Point imgPoint = new Point((map.Width - logosize) / 2, (map.Height - logosize) / 2);
                g.DrawImage(img, imgPoint.X, imgPoint.Y, logosize, logosize);
                map.Save(ms, ImageFormat.Png);
            }

            return(ms.GetBuffer());
        }
        Bitmap ComputeQRCode(int slice)
        {
            var qrEncoder = new QrEncoder(FErrorCorrectionLevel[slice]);
            var qrCode    = new QrCode();

            if (qrEncoder.TryEncode(FText[slice], out qrCode))
            {
                using (var fore = new SolidBrush(FForeColor[slice].Color))
                    using (var back = new SolidBrush(FBackColor[slice].Color))
                    {
                        var         renderer = new GraphicsRenderer(new FixedModuleSize(FPixelSize[slice], FQuietZoneModules[slice]), fore, back);
                        DrawingSize dSize    = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width);
                        var         bmp      = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                        using (var g = Graphics.FromImage(bmp))
                            renderer.Draw(g, qrCode.Matrix);


                        return(bmp);
                    }
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 生成带Logo二维码
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="iconPath">logo路径</param>
        /// <param name="moduleSize">二维码的大小</param>
        /// <returns>输出流</returns>
        public static MemoryStream GetQRCode(string content, string iconPath, int moduleSize = 9)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(content);

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);

            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            //PS:追加的图片过大超过二维码的容错率会导致信息丢失,无法被识别
            System.Drawing.Image img = System.Drawing.Image.FromFile(iconPath);

            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);

            MemoryStream memoryStream = new MemoryStream();

            map.Save(memoryStream, ImageFormat.Jpeg);

            return(memoryStream);

            //生成图片的代码: map.Save(fileName, ImageFormat.Jpeg);//fileName为存放的图片路径
        }
Exemplo n.º 4
0
        public byte[] GetGetQrCode(string content)
        {
            try
            {
                using (MemoryStream imgStream = new MemoryStream())
                {
                    QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

                    QrCode qr;

                    int ModuleSize = 12;                                //大小

                    QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域


                    if (qrEncoder.TryEncode(content, out qr))//对内容进行编码,并保存生成的矩阵
                    {
                        //Brush b = new SolidBrush(Color.FromArgb(20, Color.Gray));
                        var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones), Brushes.Black, Brushes.Transparent);
                        //render.WriteToStream(qr.Matrix, ImageFormat.Png, imgStream);

                        //logo
                        DrawingSize dSize = render.SizeCalculator.GetSize(qr.Matrix.Width);
                        Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                        Graphics    g     = Graphics.FromImage(map);
                        render.Draw(g, qr.Matrix);

                        //logo
                        //Image img = resizeImage(Image.FromFile(@"D:\code\learn\asp.net\0-part\webapi\WebApiTest\webapi1\Images\logo1.png"), new Size(100, 100));
                        //img.Save(@"D:\code\learn\asp.net\0-part\webapi\WebApiTest\webapi1\Images\qrlogo.png", ImageFormat.Png);

                        //Image img = Image.FromFile(@"D:\code\Projects\速星创\server\SXC\SXC.WebApi\Images\qrlogo.png");

                        Image img = Image.FromFile(Function.GetImagePath("qrlogo.png"));

                        Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);
                        g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);

                        map.Save(imgStream, ImageFormat.Png);

                        byte[] imgByte = imgStream.GetBuffer();

                        img.Dispose();
                        g.Dispose();
                        map.Dispose();

                        return(imgByte);
                    }
                    else
                    {
                        throw new Exception("二维码生成失败");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 5
0
        public override void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
        {
            this.size = pixelSize;

            context = target.DeviceManager.ContextDirect2D;
            pixelBrush = new SolidColorBrush(context, color);
            dimmingBrush = new SolidColorBrush(context, new Color(0, 0, 0, 10));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 根据文字内容等信息构建相应QRCode格式二维码图片
        /// </summary>
        /// <param name="content">二维码内容信息</param>
        /// <param name="level">纠错级别</param>
        /// <param name="width">图片宽度,如小于0则使用默认尺寸</param>
        /// <param name="height">图片高度,如小于0则使用默认尺寸</param>
        /// <param name="inline">内嵌图片,如为Null则不做内嵌</param>
        /// <returns>二维码图片</returns>
        public static Image BuildQRCode(String content, ErrorCorrectionLevel level, int width, int height, Image inline)
        {
            QrEncoder encoder = new QrEncoder(level);
            QrCode    code    = null;

            if (!encoder.TryEncode(content, out code))
            {
                return(null);
            }


            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(ModuleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            DrawingSize      cSize  = render.SizeCalculator.GetSize(code.Matrix.Width);
            Size             oSize  = new Size(cSize.CodeWidth, cSize.CodeWidth) + new Size(2 * PaddingSizeInPixels, 2 * PaddingSizeInPixels);

            Image img = new Bitmap(oSize.Width, oSize.Height);

            using (Graphics g = Graphics.FromImage(img))
            {
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode  = InterpolationMode.HighQualityBicubic;

                render.Draw(g, code.Matrix);
                if (inline != null)
                {
                    int iw = (int)(oSize.Width * InlineSizeInProportion);
                    int ih = (int)(oSize.Height * InlineSizeInProportion);
                    int il = (oSize.Width - iw) / 2;
                    int it = (oSize.Height - ih) / 2;
                    g.DrawImage(inline, it, il, iw, ih);
                    Pen pen = new Pen(Color.White, 1);
                    using (GraphicsPath path = CreateRoundedRectanglePath(new Rectangle(it - 1, il - 1, iw + 1, ih + 1), 4))
                    {
                        g.DrawPath(pen, path);
                    }
                }
            }

            if (width > 0 && height > 0)
            {
                int   w       = width > 0 ? width : code.Matrix.Width;
                int   h       = height > 0 ? height : code.Matrix.Height;
                Image imgCode = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage(imgCode))
                {
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(img, 0, 0, width, height);
                }

                img.Dispose();
                img = imgCode;
            }


            return(img);
        }
Exemplo n.º 7
0
        //[Route("api/XXQrCode/{content}")]
        //[HttpGet]
        public HttpResponseMessage GetQrCodeX(string content)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

            QrCode qr;

            int ModuleSize = 12;                                //大小

            QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域

            MemoryStream imgStream = new MemoryStream();

            if (qrEncoder.TryEncode(content, out qr))//对内容进行编码,并保存生成的矩阵
            {
                //Brush b = new SolidBrush(Color.FromArgb(20, Color.Gray));
                var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones), Brushes.Black, Brushes.Transparent);
                //render.WriteToStream(qr.Matrix, ImageFormat.Png, imgStream);

                //logo
                DrawingSize dSize = render.SizeCalculator.GetSize(qr.Matrix.Width);
                Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                Graphics    g     = Graphics.FromImage(map);
                render.Draw(g, qr.Matrix);

                //logo
                //Image img = resizeImage(Image.FromFile(@"D:\code\learn\asp.net\0-part\webapi\WebApiTest\webapi1\Images\logo1.png"), new Size(100, 100));
                //img.Save(@"D:\code\learn\asp.net\0-part\webapi\WebApiTest\webapi1\Images\qrlogo.png", ImageFormat.Png);

                //Image img = Image.FromFile(@"D:\code\Projects\速星创\server\SXC\SXC.WebApi\Images\qrlogo.png");

                Image img = Image.FromFile(@"D:\code\Projects\速星创\server\SXC\SXC.WebApi\Images\qrlogo.png");

                Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);
                g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);

                map.Save(imgStream, ImageFormat.Png);

                img.Dispose();
                g.Dispose();

                var resp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(imgStream.GetBuffer())
                              //或者
                              //Content = new StreamContent(imgStream)
                };
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

                return(resp);
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 8
0
        public Image getqrcode(string content)
        {
            var              encoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode  = encoder.Encode(content);
            GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(12, QuietZoneModules.Two), Brushes.Black, Brushes.White);//如需改变二维码大小,调整12即可
            DrawingSize      dSize   = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap           map     = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics         g       = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            return(map);
        }
Exemplo n.º 9
0
        internal void Save(XElement xParent)
        {
            var nfi = new NumberFormatInfo();

            nfi.NumberDecimalSeparator = ".";

            xParent.Add(
                new XElement("Drawing",
                             new XAttribute("Name", DrawingName),
                             new XElement("ExportFormat", ExportFormat.ToString()),
                             new XElement("DrawingSize", DrawingSize.ToString(nfi)),
                             new XElement("SaveDrawingSize", SaveDrawingSize.ToString())));
        }
Exemplo n.º 10
0
            public void SaveTo(string filename)
            {
                var file = new IniFile();

                file["PARAMETERS"]["WIDTH"]  = Width.ToString(CultureInfo.InvariantCulture);
                file["PARAMETERS"]["HEIGHT"] = Height.ToString(CultureInfo.InvariantCulture);

                file["PARAMETERS"]["X_OFFSET"] = XOffset.ToString(CultureInfo.InvariantCulture);
                file["PARAMETERS"]["Z_OFFSET"] = ZOffset.ToString(CultureInfo.InvariantCulture);

                file["PARAMETERS"]["MARGIN"]       = Margin.ToString(CultureInfo.InvariantCulture);
                file["PARAMETERS"]["SCALE_FACTOR"] = ScaleFactor.ToString(CultureInfo.InvariantCulture);
                file["PARAMETERS"]["DRAWING_SIZE"] = DrawingSize.ToString(CultureInfo.InvariantCulture);

                file.Save(filename);
            }
        public override void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
        {
            this.drawingSize = pixelSize;
            this.size = new DrawingSize((int) (pixelSize.Width/scaling), (int) (pixelSize.Height/scaling));
            context = target.DeviceManager.ContextDirect2D;

            Mandelbrot engine = new BasicMandelbrot(iters);
            view = new TrajectoryMandelbrotView(engine, trajectory, size.Width, size.Height);

            data = new int[size.Width * size.Height];

            PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
            BitmapProperties props = new BitmapProperties(format);

            buf = Bitmap.New<int>(context, size, data, props);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 生成二维码的方法
        /// </summary>
        /// <param name="str">二维码包含的内容</param>
        /// <param name="moduleSize">二维码大小</param>
        /// <param name="no">编号</param>
        private void createQrCode(string content, int no, int moduleSize = 9)
        {
            //QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            //QrCode qrCode = new QrCode();
            //qrEncoder.TryEncode(str, out qrCode);

            string filename = DateTime.Now.ToString("d");

            filename = filename.Replace("/", "");
            filename = filename.Replace(":", "");
            filename = filename.Replace("-", "");
            filename = filename.Replace(".", "");
            filename = filename.Replace(" ", "");
            string filepath = System.AppDomain.CurrentDomain.BaseDirectory + filename;

            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }

            string fileName = filepath + "\\" + no + ".png";
            //Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);
            //renderer.CreateImageFile(qrCode.Matrix, @filename, ImageFormat.Png);



            //ErrorCorrectionLevel 误差校正水平
            //QuietZoneModules     空白区域

            var              encoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode  = encoder.Encode(content);
            GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            //MemoryStream memoryStream = new MemoryStream();
            //render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, memoryStream);

            //return memoryStream;

            //生成图片的代码
            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            map.Save(fileName, ImageFormat.Png);//fileName为存放的图片路径
        }
Exemplo n.º 13
0
        void RenderPass(Common.Region dc, Common.Size ReqSize)
        {
            renderTime.Start();
            // Resize the form and backbuffer to noForm.Size
            Resize(ReqSize);

            Win32Util.Size w32Size = new Win32Util.Size((int)ReqSize.width, (int)ReqSize.height);
            Win32Util.SetWindowSize(w32Size, winHandle); // FIXME blocks when closing->endrender event is locked...

            // Allow noform size to change as requested..like a layout hook (truncating layout passes with the render passes for performance)
            RenderSizeChanged(ReqSize);

            // Do Drawing stuff
            DrawingSize rtSize = new DrawingSize((int)d2dRenderTarget.Size.Width, (int)d2dRenderTarget.Size.Height);

            using (Texture2D t2d = new Texture2D(backBuffer.Device, backBuffer.Description))
            {
                using (Surface1 srf = t2d.QueryInterface <Surface1>())
                {
                    using (RenderTarget trt = new RenderTarget(d2dFactory, srf, new RenderTargetProperties(d2dRenderTarget.PixelFormat)))
                    {
                        _backRenderer.renderTarget = trt;
                        trt.BeginDraw();
                        noForm.DrawBase(this, dc);
                        trt.EndDraw();

                        foreach (var rc in dc.AsRectangles())
                        {
                            t2d.Device.CopySubresourceRegion(t2d, 0,
                                                             new ResourceRegion()
                            {
                                Left = (int)rc.left, Right = (int)rc.right, Top = (int)rc.top, Bottom = (int)rc.bottom, Back = 1, Front = 0
                            }, backBuffer, 0,
                                                             (int)rc.left, (int)rc.top, 0);
                        }
                    }
                }
            }
            swapchain.Present(0, PresentFlags.None);

            //System.Threading.Thread.Sleep(1000);
            lastFrameRenderDuration = 1f / (float)renderTime.Elapsed.TotalSeconds;
            renderTime.Reset();
        }
Exemplo n.º 14
0
        private int CalculateSuitableWidth(int width, int bitMatrixWidth)
        {
            FixedCodeSize isize = new FixedCodeSize(width, m_QuietZoneModule);
            DrawingSize   dSize = isize.GetSize(bitMatrixWidth);
            int           gap   = dSize.CodeWidth - dSize.ModuleSize * (bitMatrixWidth + 2 * (int)m_QuietZoneModule);

            if (gap == 0)
            {
                return(width);
            }
            else if (dSize.CodeWidth / gap < 6)
            {
                return((dSize.ModuleSize + 1) * (bitMatrixWidth + 2 * (int)m_QuietZoneModule));
            }
            else
            {
                return(dSize.ModuleSize * (bitMatrixWidth + 2 * (int)m_QuietZoneModule));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="Content">内容文本</param>
        /// <param name="size">图片尺寸(像素),0表示不设置</param>
        /// <returns></returns>
        public string CreateQRCode(string Content, int Size)
        {
            Graphics         g         = null;
            Bitmap           img       = null;
            QrEncoder        qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode    = qrEncoder.Encode(Content);
            GraphicsRenderer render    = new GraphicsRenderer(new FixedModuleSize(Size, QuietZoneModules.Four), Brushes.Black, Brushes.White);
            Point            padding   = new Point(10, 10);
            DrawingSize      dSize     = render.SizeCalculator.GetSize(qrCode.Matrix.Width);

            img = new Bitmap(dSize.CodeWidth + padding.X, dSize.CodeWidth + padding.Y);
            //创建GDI绘图图面对象
            g = Graphics.FromImage(img);
            render.Draw(g, qrCode.Matrix, padding);
            //创建文件夹
            Common.CreateDir(filePath);
            //文件名称
            string guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";

            RelativePath += guid;
            string QRCodePath = filePath + "/" + guid;

            try
            {
                using (FileStream stream = new FileStream(QRCodePath, FileMode.Create))
                {
                    render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                }
            }
            catch (Exception e)
            {
                string ServiceName = "SaveQRCode";
                string LogBody     = "---执行服务出现错误,异常信息:" + e.Message + ",时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "---\r\n";
                Common.WriteLogFile(Common.getErrorLogFile(ServiceName), LogBody);
            }
            finally
            {
                //释放占用资源
                img.Dispose();
                g.Dispose();
            }
            return(RelativePath);
        }
Exemplo n.º 16
0
        private void logoEncode(string filename, string source, string logoPath)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(source);
            //保存成png文件
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            Image img      = Image.FromFile(logoPath);
            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);
            map.Save(filename, ImageFormat.Png);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the QR code containing the data of the network component.
        /// </summary>
        /// <returns>The QR code image.</returns>
        public Bitmap GetQRCode( )
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

            byte[] ipBytes = IP.GetAddressBytes( );
            QrCode qrCode  = qrEncoder.Encode($"{string.Join( ",", ipBytes )},{Port}");


            const int        moduleSizeInPixels = 25;
            GraphicsRenderer renderer           = new GraphicsRenderer(new FixedModuleSize(moduleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            DrawingSize dSize = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width);

            Bitmap bmp = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);

            using (Graphics graphics = Graphics.FromImage(bmp))
                renderer.Draw(graphics, qrCode.Matrix);

            return(bmp);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 二维码生成
        /// </summary>
        /// <param name="content"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        private System.Drawing.Image MakeTryQRCode(string content, string title)
        {
            QrEncoder        qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode    = qrEncoder.Encode(content);
            GraphicsRenderer render    = new GraphicsRenderer(new FixedModuleSize(15, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            DrawingSize      dSize     = render.SizeCalculator.GetSize(qrCode.Matrix.Width);

            Bitmap bitmap = new Bitmap(dSize.CodeWidth + 10, dSize.CodeWidth + 114);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                //背景色:白
                g.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);
                //描画二维码
                render.Draw(g, qrCode.Matrix, new Point(10, 10));

                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //描画中间的log
                string logFile = Path.Combine(Application.StartupPath, "logo.png");
                if (File.Exists(logFile))
                {
                    Size  size  = new Size(160, 160);
                    Point point = new Point(bitmap.Width / 2 - size.Width / 2, bitmap.Width / 2 - size.Height / 2);
                    //描画背景
                    g.FillEllipse(Brushes.White, point.X, point.Y, size.Width, size.Height);
                    //描画logo
                    System.Drawing.Image img     = Bitmap.FromFile(logFile);
                    TextureBrush         texture = new TextureBrush(img);
                    texture.TranslateTransform(-75, -80);
                    texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
                    g.FillEllipse(texture, point.X + 8, point.Y + 8, size.Width - 16, size.Height - 16);
                }
                //描画下面的描述性文字
                StringFormat sf = new StringFormat();
                sf.Alignment     = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Near;
                sf.FormatFlags   = StringFormatFlags.NoWrap;
                g.DrawString(title, new Font("Simhei", 32f, FontStyle.Bold), Brushes.Black, new RectangleF(30, bitmap.Height - 100, bitmap.Width - 60, 100), sf);
            }
            return(bitmap);
        }
Exemplo n.º 19
0
        //生成带Logo的二维码
        static void Generate5()
        {
            QrEncoder qrEncoder = new QrEncoder();
            var       qrCode    = qrEncoder.Encode("我是小天马");
            //保存成png文件
            string           filename = @"H:\桌面\截图\logo.png";
            GraphicsRenderer render   = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            Image img = Image.FromFile(@"F:\JavaScript_Solution\QrCode\QrCode\Images\101.jpg");

            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);
            map.Save(filename, ImageFormat.Png);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 生成带logo的二维码
        /// </summary>
        public static void GenerateLogoQr()
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode("http://www.yunfangdata.com");
            //保存成png文件
            string           filename = System.Environment.CurrentDirectory + "\\二维码.png"; //@"H:\桌面\截图\logo.png";
            GraphicsRenderer render   = new GraphicsRenderer(new FixedModuleSize(10, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            Image img = Image.FromFile(System.Environment.CurrentDirectory + "\\img\\logo2.png");

            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);
            map.Save(filename, ImageFormat.Png);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Loads a Direct2D Bitmap from a file using System.Drawing.Image.FromFile(...)
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <param name="file">The file.</param>
        /// <returns>A D2D1 Bitmap</returns>
        public static Bitmap LoadFromFile(RenderTarget renderTarget, string file)
        {
            // Loads from file using System.Drawing.Image
            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 DrawingSize(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                int stride = bitmap.Width * sizeof(int);
                using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                {
                    // Lock System.Drawing.Bitmap
                    var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                    // Convert all pixels 
                    for (int y = 0; y < bitmap.Height; y++)
                    {
                        int offset = bitmapData.Stride*y;
                        for (int x = 0; x < bitmap.Width; x++)
                        {
                            // Not optimized 
                            byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            int rgba = R | (G << 8) | (B << 16) | (A << 24);
                            tempStream.Write(rgba);
                        }
                        
                    }
                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;

                    return new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);
                }
            }
        }
Exemplo n.º 22
0
        public static void RunSample2()
        {
            const string helloWorld = "Hello World!";

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = qrEncoder.Encode(helloWorld);

            const int        moduleSizeInPixels = 5;
            GraphicsRenderer renderer           = new GraphicsRenderer(new FixedModuleSize(moduleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            Panel       panel   = new Panel();
            Point       padding = new Point(10, 16);
            DrawingSize dSize   = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width);

            panel.AutoSize = false;
            panel.Size     = new Size(dSize.CodeWidth, dSize.CodeWidth) + new Size(2 * padding.X, 2 * padding.Y);

            using (Graphics graphics = panel.CreateGraphics())
            {
                renderer.Draw(graphics, qrCode.Matrix, padding);
            }
        }
Exemplo n.º 23
0
        public static Bitmap GenerateQRCode(string text)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(text);

            //ModuleSize 设置图片大小
            //QuietZoneModules 设置周边padding

            /*
             * 5----150*150    padding:5
             * 10----300*300   padding:10
             */
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(10, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            Point       padding = new Point(10, 10);
            DrawingSize dSize   = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map     = new Bitmap(dSize.CodeWidth + padding.X, dSize.CodeWidth + padding.Y);
            Graphics    g       = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix, padding);
            return(map);
        }
Exemplo n.º 24
0
        private Bitmap LoadFromFile(string file)
        {
            // Loads from file using System.Drawing.Image
            using (var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile("Ressources\\Graphics\\" + file + ".png"))
            {
                var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                var bitmapProperties = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                var size             = new DrawingSize(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                int stride = bitmap.Width * sizeof(int);
                using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                {
                    // Lock System.Drawing.Bitmap
                    var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                    // Convert all pixels
                    for (int y = 0; y < bitmap.Height; y++)
                    {
                        int offset = bitmapData.Stride * y;
                        for (int x = 0; x < bitmap.Width; x++)
                        {
                            // Not optimized
                            byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                            tempStream.Write(rgba);
                        }
                    }
                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;

                    return(new Bitmap(_RenderTarget, size, tempStream, stride, bitmapProperties));
                }
            }
        }
Exemplo n.º 25
0
        //设置二维码大小
        public static void Generate4()
        {
            QrEncoder qrEncoder = new QrEncoder();
            QrCode    qrCode    = qrEncoder.Encode("我是小天马");
            //保存成png文件
            string filename = @"D:\09VS\08temp\size.png";
            //ModuleSize 设置图片大小
            //QuietZoneModules 设置周边padding

            /*
             * 5----150*150    padding:5
             * 10----300*300   padding:10
             */
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(10, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            Point       padding = new Point(10, 10);
            DrawingSize dSize   = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map     = new Bitmap(dSize.CodeWidth + padding.X, dSize.CodeWidth + padding.Y);
            Graphics    g       = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix, padding);
            map.Save(filename, ImageFormat.Png);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="source">源字符</param>
        /// <param name="setting">二维码生成设置</param>
        public static Image CreateQRCode(this string source, QRCodeSetting setting = null)
        {
            if (setting == null)
            {
                setting = new QRCodeSetting();
            }
            var level     = setting.ErrorCorrectionLevel == null ? Gma.QrCodeNet.Encoding.ErrorCorrectionLevel.H : (Gma.QrCodeNet.Encoding.ErrorCorrectionLevel)setting.ErrorCorrectionLevel;
            var pieceSize = setting.PieceSize ?? 1;
            var foreColor = setting.ForeColor ?? Color.Black;
            var backColor = setting.BackColor ?? Color.White;
            var zone      = setting.QuietZoneModule == null ? Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules.Two : (Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules)setting.QuietZoneModule;

            QrEncoder        encoder = new QrEncoder(level);
            QrCode           code    = encoder.Encode(source);
            GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(pieceSize, zone), new SolidBrush(foreColor), new SolidBrush(backColor));
            DrawingSize      dSize   = render.SizeCalculator.GetSize(code.Matrix.Width);

            var image = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);

            using (Graphics g = Graphics.FromImage(image))
                render.Draw(g, code.Matrix);
            return(image);
        }
Exemplo n.º 27
0
        //生成带Logo的二维码
        public static void Generate5()
        {
            QrEncoder qrEncoder = new QrEncoder();
            QrCode    qrCode    = qrEncoder.Encode("我是小天马");
            //保存成png文件
            string           filename = @"D:\09VS\08temp\logo.png";
            GraphicsRenderer render   = new GraphicsRenderer(new FixedModuleSize(35, QuietZoneModules.Four), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap      map   = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics    g     = Graphics.FromImage(map);

            render.Draw(g, qrCode.Matrix);
            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            Image img = Image.FromFile(@"D:\09VS\08temp\Images\101.jpg");

            System.Diagnostics.Debug.Print(map.Width + "-- " + map.Height);
            System.Diagnostics.Debug.Print(img.Width + "//" + img.Height);
            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);
            map.Save(filename, ImageFormat.Png);
        }
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="moduleSize">二维码的大小</param>
        /// <returns>输出流</returns>
        public static string GetQRCode(string content, string realname, string filename, int moduleSize = 9)
        {
            var r = "";

            try
            {
                var              encoder = new QrEncoder(ErrorCorrectionLevel.M);
                QrCode           qrCode  = encoder.Encode(content);
                GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                MemoryStream memoryStream = new MemoryStream();
                render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, memoryStream);

                //生成图片的代码
                DrawingSize dSize  = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
                Bitmap      bitmap = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                // var filename = Guid.NewGuid().ToString().Replace("-", "");
                var filesavepath = "Files/" + realname + "/QRPic";
                var _fileExits   = System.Web.HttpContext.Current.Server.MapPath("~/" + filesavepath);
                if (!Directory.Exists(_fileExits))
                {
                    Directory.CreateDirectory(_fileExits);
                }
                string fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + filesavepath + "/" + filename + ".jpg";

                Graphics g = Graphics.FromImage(bitmap);
                render.Draw(g, qrCode.Matrix);
                bitmap.Save(fileName, ImageFormat.Jpeg);
                r = filesavepath + "/" + filename + ".jpg";
            }
            catch (Exception ex)
            {
                var abc = ex.Message;
            }
            return(r);
        }
Exemplo n.º 29
0
        TextureAsset IAssetManager.LoadTexture(string file)
        {
            Bitmap result = null;
            if (_bitmapResources.TryGetValue(file, out result) && !result.IsDisposed)
                return new TextureAsset(result);

            Stream stream;
            if (File.Exists(RootDirectory + file))
                stream = File.OpenRead(RootDirectory + file);
            else if (File.Exists(file))
                stream = File.OpenRead(file);
            else {
                stream = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                          from name in assembly.GetManifestResourceNames()
                          where String.Compare(file, name, true) != 0
                          select assembly.GetManifestResourceStream(name)).FirstOrDefault();
            }

            if (stream == null) {
                Console.Error.WriteLine("Failed to load bitmap asset: {0}", file);
                // TODO: Have some sort of placeholder texture to feed back, even a single pixel
                return null;
            }

            try {
                using (var newBitmap = new System.Drawing.Bitmap(stream)) {

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

                    // Transform pixels from BGRA to RGBA
                    int stride = newBitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(newBitmap.Height * stride, true, true)) {
                        // Lock System.Drawing.Bitmap
                        var bitmapData = newBitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                        // Convert all pixels
                        for (int y = 0; y < newBitmap.Height; y++) {
                            int offset = bitmapData.Stride * y;
                            for (int x = 0; x < newBitmap.Width; x++) {
                                // Not optimized
                                byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                int rgba = R | (G << 8) | (B << 16) | (A << 24);
                                tempStream.Write(rgba);
                            }

                        }
                        newBitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;

                        try {
                            result = new Bitmap(_renderTarget2D, size, tempStream, stride, bitmapProperties);
                        } catch (NullReferenceException) {
                            throw new AssetLoadException("Graphics device uninitialized");
                        }
                    }
                }
            } catch (ArgumentException) {
                Console.Error.WriteLine("Invalid data stream while loading bitmap data");
            } finally {
                stream.Dispose();
            }
            _bitmapResources.AddOrUpdate(file, result, (key, oldValue) => {
                if (!oldValue.IsDisposed)
                    oldValue.Dispose();
                return result;
            });
            return new TextureAsset(result);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Returns the closest dimensions the implementation can natively scale to given the desired dimensions.
 /// </summary>
 /// <param name="size">The size.</param>
 /// <returns></returns>
 /// <unmanaged>HRESULT IWICBitmapSourceTransform::GetClosestSize([InOut] unsigned int* puiWidth,[InOut] unsigned int* puiHeight)</unmanaged>
 public void GetClosestSize(ref DrawingSize size)
 {
     int width = size.Width;
     int height = size.Height;
     GetClosestSize(ref width, ref height);
     size.Width = width;
     size.Height = height;
 }
        private void load(Object sender, RoutedEventArgs e)
        {
            // Create bitmap and set it to black
            ImageBrush d2dBrush = new ImageBrush();
            d2dRectangle.Fill = d2dBrush;

            DeviceManager deviceManager = new DeviceManager();

            DrawingSize size = new DrawingSize((int)d2dContainer.ActualWidth, (int)d2dContainer.ActualHeight);

            d2dTarget = new SurfaceImageSourceTarget(size.Width, size.Height);
            d2dBrush.ImageSource = d2dTarget.ImageSource;

            deviceManager.OnInitialize += d2dTarget.Initialize;
            deviceManager.Initialize(DisplayProperties.LogicalDpi);

            d2dTarget.OnRender += item.drawContent;
            item.initContent(d2dTarget, size);

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Exemplo n.º 32
0
        /// <summary>
        /// 生成带二维码海报
        /// </summary>
        /// <param name="url">二维码跳转链接</param>
        /// <param name="headImg">海报顶部图片</param>
        /// <param name="headTitle">海报顶部文字</param>
        /// <param name="headTitle">海报二维码中部文字</param>
        /// <param name="logoImg">海报二维码内的logo</param>
        /// <returns></returns>
        public static string CreatePoster(string url, string headImg, string headTitle, string bodyTitle, string logoImg)
        {
            var posPath = "";

            try
            {
                //先画个最大的黑色背景
                Bitmap   ob = new Bitmap(414, 736);
                Graphics g  = Graphics.FromImage(ob);
                g.InterpolationMode  = InterpolationMode.High;
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode      = SmoothingMode.AntiAlias;
                g.Clear(ColorTranslator.FromHtml("#333333"));

                //画一个白的底板
                Bitmap   white = new Bitmap(ob.Width, ob.Height - 15);
                Graphics gw    = Graphics.FromImage(white);
                gw.Clear(Color.White);
                g.DrawImage(white, new Rectangle(0, 0, white.Width, white.Height));
                white?.Dispose();
                gw?.Dispose();
                //顶部图片
                Bitmap head = new Bitmap(headImg);
                //图片高度
                int headHeight = head.Height * ob.Width / head.Width;//保持横纵比例
                g.DrawImage(head, 0, 0, ob.Width, headHeight);
                head?.Dispose();
                //画顶部图片 中的文字
                SolidBrush   txtBrush  = new SolidBrush(Color.White);
                StringFormat txtFromat = new StringFormat
                {
                    Alignment = StringAlignment.Center
                };
                g.DrawString(headTitle, new Font("黑体", 20, FontStyle.Bold), txtBrush, new Point(ob.Width / 2, 50), txtFromat);
                //二维码上部文字描述
                txtBrush = new SolidBrush(ColorTranslator.FromHtml("#333333"));
                //处理文字不能超过40个
                string bodyStr = "";
                if (bodyTitle.Length > 40)
                {
                    bodyTitle = bodyTitle.Substring(0, 40);
                }
                if (bodyTitle.Length > 20)
                {
                    bodyStr += bodyTitle.Substring(0, 20);
                    bodyStr += "\r\n";
                    bodyStr += bodyTitle.Substring(0, 20);
                }
                else
                {
                    bodyStr = bodyTitle;
                }
                g.DrawString(bodyStr, new Font("黑体", 20, FontStyle.Bold), txtBrush, new Point(ob.Width / 2, headHeight + 20), txtFromat);
                //二维码地址
                var              encoder = new QrEncoder(ErrorCorrectionLevel.M);//设置二维码的容错率
                QrCode           qrCode  = encoder.Encode(url);
                GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(23, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                DrawingSize      dSize   = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
                //创建存储二维码的图片
                Bitmap   map3 = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                Graphics g2   = Graphics.FromImage(map3);
                render.Draw(g2, qrCode.Matrix);
                //将logo添加到二维码图片上
                Image logo      = Image.FromFile(logoImg);
                int   logowidth = (int)(dSize.CodeWidth * 0.1);
                Point iconPoint = new Point((map3.Width - logowidth) / 2, (map3.Height - logowidth) / 2);
                g2.DrawImage(logo, iconPoint.X, iconPoint.Y, logowidth, logowidth);
                //将二维码图片画到最开始的那张图片上
                g.DrawImage(map3, new Rectangle(ob.Width / 4, headHeight + 75, ob.Width / 2, ob.Width / 2));
                map3?.Dispose();
                g2?.Dispose();
                logo?.Dispose();
                //处理长按复制文字
                txtBrush = new SolidBrush(ColorTranslator.FromHtml("#9F9F9F"));
                g.DrawString("长按识别二维码查看产品详情", new Font("黑体", 10), txtBrush, new Point(ob.Width / 2, headHeight + ob.Width / 2 + 95), txtFromat);

                string savePath = $"D:{Path.DirectorySeparatorChar}Temp{Path.DirectorySeparatorChar}{Guid.NewGuid()}.png";
                ob.Save(savePath, ImageFormat.Png);
                ob?.Dispose();
                g?.Dispose();
                posPath = savePath;
            }
            catch (Exception ex)
            {
                posPath = "";
            }
            return(posPath);
        }
Exemplo n.º 33
0
 public virtual void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
 {
 }
Exemplo n.º 34
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size)
     : this(deviceContext, size, null, 0, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }
Exemplo n.º 35
0
        private SharpDX.WIC.FormatConverter DecodeImage()
        {
            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                                                                                        _deviceManager.WICFactory,
                                                                                        @"Assets\Nepal.jpg",
                                                                                        SharpDX.IO.NativeFileAccess.Read,
                                                                                        SharpDX.WIC.DecodeOptions.CacheOnDemand
                                                                                    );

            SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);

            SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer);

            SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(_deviceManager.WICFactory);
            //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA);
            formatConverter.Initialize(
                bitmapSource,
                SharpDX.WIC.PixelFormat.Format32bppBGRA, 
                SharpDX.WIC.BitmapDitherType.None, 
                null, 
                0.0f, 
                SharpDX.WIC.BitmapPaletteType.Custom
                );

            imageSize = formatConverter.Size;
            
            return formatConverter;
        }
Exemplo n.º 36
0
 private static Texture2DDescription CreateTextureDescription(DrawingSize size)
 {
     return new Texture2DDescription
     {
         Width = size.Width,
         Height = size.Height,
         ArraySize = 1,
         BindFlags = BindFlags.ShaderResource,
         Usage = ResourceUsage.Immutable,
         CpuAccessFlags = CpuAccessFlags.None,
         Format = Format.R8G8B8A8_UNorm,
         MipLevels = 1,
         OptionFlags = ResourceOptionFlags.None,
         SampleDescription = new SampleDescription(1, 0),
     };
 }
Exemplo n.º 37
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, DataStream dataStream, int pitch, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmap(size, dataStream == null ? IntPtr.Zero : dataStream.PositionPointer, pitch, bitmapProperties, this);
 }
Exemplo n.º 38
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, DataStream dataStream, int pitch)
     : this(deviceContext, size, dataStream, pitch, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }
Exemplo n.º 39
0
 /// <summary>	
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.	
 /// </summary>	
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>	
 public Bitmap1(DeviceContext deviceContext, DrawingSize size, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : this(deviceContext, size, null, 0, bitmapProperties)
 {
 }
Exemplo n.º 40
0
        void RenderPass(Common.Region dc, Common.Size ReqSize)
        {
            renderTime.Start();
            // FIXME so much object spam and disposal in this very high frequency function (also inside Resize called belw).  My poor megabytes!

            // Resize the form and backbuffer to noForm.Size, and fire the noForms sizechanged
            Resize(ReqSize);

            // make size...
            Win32Util.Size w32Size = new Win32Util.Size((int)ReqSize.width, (int)ReqSize.height);
            Win32Util.SetWindowSize(w32Size, hWnd);

            // Allow noform size to change as requested..like a layout hook (truncating layout passes with the render passes for performance)
            RenderSizeChanged(ReqSize);

            lock (noForm)
            {
                // Do Drawing stuff
                DrawingSize rtSize = new DrawingSize((int)d2dRenderTarget.Size.Width, (int)d2dRenderTarget.Size.Height);
                using (Texture2D t2d = new Texture2D(backBuffer.Device, backBuffer.Description))
                {
                    using (Surface1 srf = t2d.QueryInterface <Surface1>())
                    {
                        using (RenderTarget trt = new RenderTarget(d2dFactory, srf, new RenderTargetProperties(d2dRenderTarget.PixelFormat)))
                        {
                            _backRenderer.renderTarget = trt;
                            trt.BeginDraw();
                            noForm.DrawBase(this, dc);
                            // Fill with transparency the edgeBuffer!
                            trt.FillRectangle(new RectangleF(0, noForm.Size.height, noForm.Size.width + edgeBufferSize, noForm.Size.height + edgeBufferSize), scbTrans);
                            trt.FillRectangle(new RectangleF(noForm.Size.width, 0, noForm.Size.width + edgeBufferSize, noForm.Size.height + edgeBufferSize), scbTrans);
                            trt.EndDraw();

                            foreach (var rc in dc.AsRectangles())
                            {
                                t2d.Device.CopySubresourceRegion(t2d, 0,
                                                                 new ResourceRegion()
                                {
                                    Left = (int)rc.left, Right = (int)rc.right, Top = (int)rc.top, Bottom = (int)rc.bottom, Back = 1, Front = 0
                                }, backBuffer, 0,
                                                                 (int)rc.left, (int)rc.top, 0);
                            }
                        }
                    }
                }

                // Present DC to windows (ugh layered windows sad times)
                IntPtr dxHdc = surface.GetDC(false);
                System.Drawing.Graphics dxdc     = System.Drawing.Graphics.FromHdc(dxHdc);
                Win32Util.Point         dstPoint = new Win32Util.Point((int)(noForm.Location.X), (int)(noForm.Location.Y));
                Win32Util.Point         srcPoint = new Win32Util.Point(0, 0);
                Win32Util.Size          pSize    = new Win32Util.Size(rtSize.Width, rtSize.Height);
                Win32Util.BLENDFUNCTION bf       = new Win32Util.BLENDFUNCTION()
                {
                    SourceConstantAlpha = 255, AlphaFormat = Win32Util.AC_SRC_ALPHA, BlendFlags = 0, BlendOp = 0
                };

                bool suc = Win32Util.UpdateLayeredWindow(hWnd, someDC, ref dstPoint, ref pSize, dxHdc, ref srcPoint, 1, ref bf, 2);

                surface.ReleaseDC();
                dxdc.Dispose();
            }
            lastFrameRenderDuration = 1f / (float)renderTime.Elapsed.TotalSeconds;
            renderTime.Reset();
        }
Exemplo n.º 41
0
 /// <summary>	
 ///  Creates a bitmap render target for use during intermediate offscreen drawing that is compatible with the current render target.	
 /// </summary>	
 /// <remarks>	
 /// The pixel size and DPI of the new render target can be altered by specifying values for desiredSize or desiredPixelSize:  If desiredSize is specified but desiredPixelSize is not, the pixel size is computed from the desired size using the parent target DPI. If the desiredSize maps to a integer-pixel size, the DPI of the compatible render target is the same as the DPI of the parent target.  If desiredSize maps to a fractional-pixel size, the pixel size is rounded up to the nearest integer and the DPI for the compatible render target is slightly higher than the DPI of the parent render target. In all cases, the coordinate (desiredSize.width, desiredSize.height) maps to the lower-right corner of the compatible render target.If the desiredPixelSize is specified and desiredSize is not, the DPI of the new render target is the same as the original render target.If both desiredSize and desiredPixelSize are specified, the DPI of the new render target is computed to account for the difference in scale.If neither desiredSize nor desiredPixelSize is specified, the new render target size and DPI match the original render target. 	
 /// </remarks>	
 /// <param name="renderTarget">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="desiredSize">The desired size of the new render target in device-independent pixels if it should be different from the original render target. For more information, see the Remarks section.</param>
 /// <param name="desiredPixelSize">The desired size of the new render target in pixels if it should be different from the original render target. For more information, see the Remarks section.</param>
 /// <param name="desiredFormat">The desired pixel format and alpha mode of the new render target. If the pixel format is set to DXGI_FORMAT_UNKNOWN, the new render target uses the same pixel format as the original render target. If the alpha mode is <see cref="SharpDX.Direct2D1.AlphaMode.Unknown"/>, the alpha mode of the new render target defaults to D2D1_ALPHA_MODE_PREMULTIPLIED. For information about supported pixel formats, see  {{Supported Pixel  Formats and Alpha Modes}}.</param>
 /// <param name="options">A value that specifies whether the new render target must be compatible with GDI.</param>
 /// <unmanaged>HRESULT CreateCompatibleRenderTarget([In, Optional] const D2D1_SIZE_F* desiredSize,[In, Optional] const D2D1_SIZE_U* desiredPixelSize,[In, Optional] const D2D1_PIXEL_FORMAT* desiredFormat,[None] D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS options,[Out] ID2D1BitmapRenderTarget** bitmapRenderTarget)</unmanaged>
 public BitmapRenderTarget(RenderTarget renderTarget, SharpDX.Direct2D1.CompatibleRenderTargetOptions options, DrawingSizeF? desiredSize, DrawingSize? desiredPixelSize, SharpDX.Direct2D1.PixelFormat? desiredFormat) : base(IntPtr.Zero)
 {
     renderTarget.CreateCompatibleRenderTarget(desiredSize, desiredPixelSize, desiredFormat, options, this);
 }
Exemplo n.º 42
0
 private void UpdateSize(TargetBase target)
 {
     var localSize = new DrawingSize((int)target.RenderTargetSize.Width, (int)target.RenderTargetSize.Height);
     if (localSize != screenSize)
     {
         screenSize = localSize;
         bitmapSourceEffect.ScaleSource = new Vector2((float)screenSize.Width / imageSize.Width, (float)screenSize.Height / imageSize.Height);
     }
 }
Exemplo n.º 43
0
 /// <summary>
 /// Creates a new D2dBitmapGraphics with specified pixel size for use during intermediate offscreen drawing
 /// that is compatible with the current D2dGraphics and has the same DPI, and pixel format
 /// as the current D2dGraphics and with the specified options</summary>        
 /// <param name="pixelSize">The desired size of the new D2dGraphics in pixels</param>
 /// <param name="options">Whether the new D2dBitmapGraphics must be compatible with GDI</param>        
 public D2dBitmapGraphics CreateCompatibleGraphics(Size pixelSize, D2dCompatibleGraphicsOptions options)
 {
     var dsize = new DrawingSize(pixelSize.Width, pixelSize.Height);
     var rt = new BitmapRenderTarget(m_renderTarget, (CompatibleRenderTargetOptions)options, null, dsize, null);
     return new D2dBitmapGraphics(rt);
 }
        /// <summary>
        /// Outputs the EPS header with mandatory declarations, variable declarations and function definitions.
        /// </summary>
        /// <param name="drawingSize">Size of the drawing.</param>
        /// <param name="stream">Output text stream</param>
        /// <remarks></remarks>
        private void OutputHeader(DrawingSize drawingSize, StreamWriter stream)
        {
            string strHeader =
                @"%!PS-Adobe-3.0 EPSF-3.0
%%Creator: Gma.QrCodeNet
%%Title: QR Code
%%CreationDate: {0:yyyyMMdd}
%%Pages: 1
%%BoundingBox: 0 0 {1} {2}
%%Document-Fonts: Times-Roman
%%LanguageLevel: 1
%%EndComments
%%BeginProlog
/w {{ {3} }} def
/h {{ {4} }} def
/q {{ {5} }} def
/s {{ {6} }} def
/W {{ w q q add add }} def
/H {{ h q q add add }} def";

            string strBoxFunctions =
                @"% Define the box functions taking X and Y coordinates of the top left corner and filling a 1 point large square
/b { newpath moveto 1 0 rlineto 0 1 rlineto -1 0 rlineto closepath fill } def
/br { newpath moveto 1.01 0 rlineto 0 1 rlineto -1.01 0 rlineto closepath fill } def
/bb { newpath moveto 1 0 rlineto 0 1.01 rlineto -1 0 rlineto closepath fill } def
/brb { newpath moveto 1.01 0 rlineto 0 1 rlineto -0.01 0 rlineto 0 0.01 rlineto -1 0 rlineto closepath fill } def";

            string strHeaderEnd =
                @"%%EndProlog
%%Page: 1 1

% Save the current state
save

% Invert the Y axis
0 W s mul translate
s s neg scale";

            stream.WriteLine(string.Format(strHeader,
                                           DateTime.UtcNow,
                                           // Use invariant culture to ensure that the dot is used as the decimal separator
                                           (drawingSize.CodeWidth).ToString(CultureInfo.InvariantCulture.NumberFormat),
                                           // Size in points of the matrix with the quiet zone
                                           (drawingSize.CodeWidth).ToString(CultureInfo.InvariantCulture.NumberFormat),
                                           drawingSize.CodeWidth/drawingSize.ModuleSize -
                                           ((int) drawingSize.QuietZoneModules*2),
                                           // Number of modules of the matrix without the quiet zone
                                           drawingSize.CodeWidth/drawingSize.ModuleSize -
                                           ((int) drawingSize.QuietZoneModules*2),
                                           (int) drawingSize.QuietZoneModules, // Number of quiet zone modules
                                           drawingSize.ModuleSize.ToString(CultureInfo.InvariantCulture.NumberFormat)));
            // Size in points of a single module

            if (m_DrawingTechnique == EpsModuleDrawingTechnique.Squares)
                stream.WriteLine(strBoxFunctions);

            stream.WriteLine(strHeaderEnd);
        }
Exemplo n.º 45
0
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                int WIDTH = 1280;
                int HEIGHT = 800;
                Mandelbrot engine = new BasicMandelbrot(64);
                MandelbrotView view = new StaticMandelbrotView(engine, -.875f, 0f, 3f, WIDTH, HEIGHT);

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                int[] data = new int[WIDTH * HEIGHT];
                for (int y = 0; y < HEIGHT; y++)
                {
                    for (int x = 0; x < WIDTH; x++)
                    {
                        float val = view.pixelAt(x, y);
                        int intVal = (int)(255 * val);
                        data[y * WIDTH + x] = 0 | intVal << 16 | intVal << 8 | intVal;
                    }
                }

                DrawingSize size = new DrawingSize(WIDTH, HEIGHT);
                PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
                BitmapProperties props = new BitmapProperties(format);
                RenderTarget target = d2dContext;
                Bitmap buf = Bitmap.New<int>(target, size, data, props);

                // Clear the target and draw some geometry with the brushes we created. Note that rectangles are
                // created specifying (start-x, start-y, end-x, end-y) coordinates; in XNA we used
                // (start-x, start-y, width, height).
                d2dContext.BeginDraw();
                d2dContext.DrawBitmap(buf, 1, BitmapInterpolationMode.Linear);
                d2dContext.EndDraw();

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }