生成帶內嵌圖片的二維碼


在博問上看到有同學在問如何實現一個帶內嵌圖片的二維碼,所以准備記錄下來,供同學們參考。

 

1、首先准備一個用於內嵌的圖片。

2、既然生成二維碼碼,那肯定需要將什么樣的內容生成二維碼,這里我用http://www.baidu.com作為生成二維碼的字符串

        private string QcodeSource
        {
            get
            {
                return "http://www.baidu.com";
            }
        }

3、我們來看看根據QcodeSource生成二維碼的方法,這里返回Byte[]。PS:這里用了 Gma.QrCodeNet.Encoding.Net35.dll 生成二維碼的庫,點擊鏈接下載

        public static byte[] GetQrCodeBitmapImage(string qrcode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(qrcode)) return null;

                // Get QrCode GraphicsRenderer
                var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                var qrCode = qrEncoder.Encode(qrcode);
                var renderer = new GraphicsRenderer(new FixedModuleSize(24, QuietZoneModules.Four), Brushes.Black, Brushes.White);

                using (var stream = new MemoryStream())
                {
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Flush();
                    return stream.ToArray();
                }
            }
            catch (Exception)
            {
                return null;
            }

        }

4、既然上面返回了圖片的Byte[],所以接下來我們把准備內嵌的圖片和這個二維碼圖片拼成一個圖片,如何將內嵌圖片編程Byte[]這里不做熬述。

        /// <summary>  
        /// 調用此函數后使此兩種圖片合並,類似相冊,有個  
        /// 背景圖,中間貼自己的目標圖片  
        /// </summary>  
        /// <param name="sourceImage">粘貼的源圖片</param>  
        /// <param name="destBitmap">粘貼的目標圖片</param>  
        public static Bitmap CombinImage(Bitmap sourceImage, Bitmap destBitmap)
        {
            if (destBitmap.Height != 250 || destBitmap.Width != 250)
            {
                destBitmap = KiResizeImage(destBitmap, 250, 250, 0);
            }

            using (var g = Graphics.FromImage(sourceImage))
            {
                //g.DrawImage(img, 照片與相框的左邊距, 照片與相框的上邊距, 照片寬, 照片高); 
                g.DrawImage(sourceImage, 0, 0, sourceImage.Width, sourceImage.Height);

                //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一層黑色邊框  
                g.DrawImage(destBitmap, sourceImage.Width / 2 - destBitmap.Width / 2, sourceImage.Width / 2 - destBitmap.Width / 2, destBitmap.Width, destBitmap.Height);
                GC.Collect();
                return sourceImage;

            }
        }

5、下面上效果圖

 

總結:生成結束,主要用了Gma.QrCodeNet.Encoding.Net35.dll 這個庫,代碼還是相對來講比較簡單的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM