C# 生成文字图片二维码

阅读更多
生成文字图片
public void CreateImage(string name, string filePath)
        {
            int wid = 400;
            int high = 200;
            Font font = new Font("Arial", 28, FontStyle.Bold);
            //绘笔颜色
            SolidBrush brush = new SolidBrush(Color.Green);
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            

            Bitmap image = new Bitmap(wid, high);
            Graphics g = Graphics.FromImage(image);
            SizeF sizef = g.MeasureString(name, font, PointF.Empty, format);
            int width = (int)(sizef.Width + 1);
            int height = (int)(sizef.Height + 1);
            image.Dispose();
            image = new Bitmap(width, height);
            //g.Clear(ColorTranslator.FromHtml("#f0f0f0"));
            g = Graphics.FromImage(image);
            g.Clear(Color.White);//Transparent
            
            RectangleF rect = new RectangleF(0, 0, width, height);
            // RectangleF rect = new RectangleF(5, 2, wid, high);
            //绘制图片
            g.DrawString(name, font, brush, rect);
            //保存图片
            image.Save(filePath, ImageFormat.Png);
            //释放对象
            g.Dispose();
            image.Dispose();
        }

效果图

通过第三方线生成二码:
int len = show.Length / 5;
						for (int j = 1; j <= len; j++)
						{							
							show = show.Insert(j*5+j-1, "\n");
						}				
						CreateImage(show, path + "dt_Site_Text/" + text + ".png");						
                        System.Uri httpUrl = new System.Uri("http://qr.topscan.com/api.php?text=" + text + "&logo=http://111.17.223.51:28080/AffixFile/dt_Site_Text/" + text + ".png");
                        req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                        req.Timeout = 180000; //设置超时值10秒
                        req.Method = "GET";
                        res = (HttpWebResponse)(req.GetResponse());
                        img = new Bitmap(res.GetResponseStream());//获取图片
                        img.Save(path + "dt_Site_Scan/" + text + ".png");//随机名*/

效果如下:
C# 生成文字图片二维码_第1张图片
通过QRCode生成二码:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;

namespace QRCodeSample
{
    public partial class QrCodeSampleApp : Form
    {
        public QrCodeSampleApp()
        {
            InitializeComponent();
        }

        private void frmSample_Load(object sender, EventArgs e)
        {
            cboEncoding.SelectedIndex = 2;
            cboVersion.SelectedIndex = 6;
            cboCorrectionLevel.SelectedIndex = 1;
        }

        private void btnEncode_Click_1(object sender, EventArgs e)
        {
            if (txtEncodeData.Text.Trim() == String.Empty)
            {
                MessageBox.Show("内容不能为空!");
                txtEncodeData.Focus();
                return;
            }
            Image image = CreateImage();
            if (image != null)
            {
                picEncode.Image = image;
            }


            string name = txtEncodeData.Text;
            int len = name.Length / 5;
            for (int i = 1; i <= len / 5; i++)
            {
           
                name = name.Insert((i * 5)+i-1, "\n");
            }
            CreateImage(name, @"E:\emulator\QRCode\QRCode\QRCodeSampleApp\Name.jpg");
        }

        private Image CreateImage()
        {
            var encoder = new QRCodeEncoder();
            String encoding = cboEncoding.Text;
            if (encoding == "Byte")
            {
                encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            }
            else if (encoding == "AlphaNumeric")
            {
                encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
            }
            else if (encoding == "Numeric")
            {
                encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
            }
            try
            {
                int scale = Convert.ToInt16(txtSize.Text);
                encoder.QRCodeScale = scale;
            }
            catch (Exception ex)
            {
                MessageBox.Show("大小参数错误!");
                return null;
            }
            try
            {
                int version = Convert.ToInt16(cboVersion.Text);
                encoder.QRCodeVersion = version;
            }
            catch (Exception ex)
            {
                MessageBox.Show("版本参数错误 !");
                return null;
            }

            string errorCorrect = cboCorrectionLevel.Text;
            if (errorCorrect == "L")
                encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
            else if (errorCorrect == "M")
                encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            else if (errorCorrect == "Q")
                encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
            else if (errorCorrect == "H")
                encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;

            String data = txtEncodeData.Text;
            Image image = encoder.Encode(data);
            return image;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            saveFileDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PNG Image|*.png";
            saveFileDialog.Title = "Save";
            saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg";
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName != "")
            {
                var fileStream = (FileStream)saveFileDialog.OpenFile();
                switch (saveFileDialog.FilterIndex)
                {
                    case 1:
                        picEncode.Image.Save(fileStream, ImageFormat.Jpeg);
                        break;

                    case 2:
                        picEncode.Image.Save(fileStream, ImageFormat.Bmp);
                        break;

                    case 3:
                        picEncode.Image.Save(fileStream, ImageFormat.Gif);
                        break;
                    case 4:
                        picEncode.Image.Save(fileStream, ImageFormat.Png);
                        break;
                }
                fileStream.Close();
            }
        }



        public void CreateImage(string name, string filePath)
        {
            int wid = 400;
            int high = 200;
            Font font = new Font("Arial", 28, FontStyle.Bold);
            //绘笔颜色
            SolidBrush brush = new SolidBrush(Color.Green);
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            

            Bitmap image = new Bitmap(wid, high);
            Graphics g = Graphics.FromImage(image);
            SizeF sizef = g.MeasureString(name, font, PointF.Empty, format);
            int width = (int)(sizef.Width + 1);
            int height = (int)(sizef.Height + 1);
            image.Dispose();
            image = new Bitmap(width, height);
            //g.Clear(ColorTranslator.FromHtml("#f0f0f0"));
            g = Graphics.FromImage(image);
            g.Clear(Color.White);
            
            RectangleF rect = new RectangleF(0, 0, width, height);
            // RectangleF rect = new RectangleF(5, 2, wid, high);
            //绘制图片
            g.DrawString(name, font, brush, rect);
            //保存图片
            image.Save(filePath, ImageFormat.Png);
            //释放对象
            g.Dispose();
            image.Dispose();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            printDialog.Document = printDocument1;
            DialogResult r = printDialog.ShowDialog();
            if (r == DialogResult.OK)
            {
                printDocument1.Print();
            }
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(picEncode.Image, 0, 0);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openFile.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PNG Image|*.png|All files (*.*)|*.*";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;
            openFile.FileName = string.Empty;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                String fileName = openFile.FileName;
                picDecode.Image = new Bitmap(fileName);
            }
        }

        private void btnDecode_Click(object sender, EventArgs e)
        {
            try
            {
                var decoder = new QRCodeDecoder();
                //QRCodeDecoder.Canvas = new ConsoleCanvas();
                String decodedString = decoder.decode(new QRCodeBitmapImage(new Bitmap(picDecode.Image)));
                txtDecodedData.Text = decodedString;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnChooseIco_Click(object sender, EventArgs e)
        {
            openFile.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PNG Image|*.png|All files (*.*)|*.*";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;
            openFile.FileName = string.Empty;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                String fileName = openFile.FileName;
                PicIco.Image = new Bitmap(fileName);
            }
        }

        private void btnCreateWithIco_Click(object sender, EventArgs e)
        {
            Image img = CreateImage();
            if (PicIco.Image != null)
            {
                picEncode.Image = CombinImage(img, PicIco.Image);
            }
            else
            {
                MessageBox.Show("请选择ICO图片 !");
            }
        }

        #region 生成带图片的二维码

        /// 
        ///     合并图片
        /// 
        /// 
        /// 
        /// 
        public static Image CombinImage(Image imgBack, Image img)
        {
            if (img.Height != 50 || img.Width != 50)
            {
                img = ResizeImage(img, 50, 50, 0);
            }
            Graphics g = Graphics.FromImage(imgBack);

            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);   

            //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框  

            //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);  

            g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);
            GC.Collect();
            return imgBack;
        }

        /// 
        ///     调用此函数后使此两种图片合并,类似相册,有个
        ///     背景图,中间贴自己的目标图片
        /// 
        /// 粘贴的源图片
        /// 粘贴的目标图片
        public static Image CombinImage(Image imgBack, string destImg)
        {
            Image img = Image.FromFile(destImg);
            return CombinImage(imgBack, img);
        }

        /// 
        ///     Resize图片
        /// 
        /// 原始Bitmap
        /// 新的宽度
        /// 新的高度
        /// 保留着,暂时未用
        /// 处理以后的图片
        public static Image ResizeImage(Image bmp, int newW, int newH, int mode)
        {
            try
            {
                Image b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                // 插值算法的质量  
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height),
                            GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}

效果如下:
C# 生成文字图片二维码_第2张图片
  • C# 生成文字图片二维码_第3张图片
  • 大小: 2.8 KB
  • C# 生成文字图片二维码_第4张图片
  • 大小: 19.6 KB
  • C# 生成文字图片二维码_第5张图片
  • 大小: 35.4 KB
  • QRCode.rar (5.2 MB)
  • 下载次数: 36
  • 查看图片附件

你可能感兴趣的:(C# 生成文字图片二维码)