Table of Contents
Why is there a second edition?
Interface preview
Home Backend Development C#.Net Tutorial Detailed introduction to the sample code of the second version of the Data Url generation tool C#

Detailed introduction to the sample code of the second version of the Data Url generation tool C#

Mar 11, 2017 pm 01:48 PM

Why is there a second edition?


 First of all, thank you to jenlynn for her message: "There are two ways to generate DATA URL, C# and HTML5. Both are the same." The generated base64 encoding seems to be different, is there any way to make them agree?"

Secondly, bugs and anomalies were discovered while studying this issue.
Bug: Image encoding judgment problem, no matter what extension, PNG encoding is used by default.
Exception: ContextSwitchDeadlock detected

Interface preview


Detailed introduction to the sample code of the second version of the Data Url generation tool C#

##Improvement methods for related issues


Picture Encoding judgment problem

Before, it was mainly because I forgot that the obtained extension was preceded by a dot.

Related code:

string ext = Path.GetExtension(path).ToLower();
                //根据文件的扩展名确定使用的编码格式
                //注意扩展名是带点的!
                switch (ext)
                {
                    case ".gif":
                        fmt = System.Drawing.Imaging.ImageFormat.Gif;
                        break;
                    case ".jpg":
                    case ".jpeg":
                        fmt = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;
                    case ".ico":
                        fmt = System.Drawing.Imaging.ImageFormat.Icon;
                        break;
                    default:
                        ext = "png";
                        break;
                }
Copy after login

ContextSwitchDeadlock detected

Solution Method description StackOverflow mentioned using BackgroundWorker, I use threads here; however, after testing, it was found that due to performance issues when TextBox displays large text, when threads interact with TextBox, if the user does not operate, the window will not die. ; Once any operation is performed, the window will not respond!
So we can only change the solution, use a compromise method, do not let the TextBox display the entire DataUrl string, only display part of it; use a variable "" to save the complete DataUrl string, and click the copy button to Copy it to the Windows clipboard.

Related code

        /// <summary>
        /// 用于保存完整的DataUrl
        /// </summary>
        private string fullDataUrl = string.Empty;
Copy after login

Use threads

                //创建线程来生成DataUrl
                System.Threading.Thread thd = new System.Threading.Thread(new ParameterizedThreadStart(buildDataUrl));
                thd.Start(textBox_saveDir.Text);
Copy after login

Use delegates

        /// <summary>
        /// TextBox委托,用于实现线程中访问窗体、组件等的线程安全性
        /// </summary>
        /// <param name="msg"></param>
        public delegate void textbox_delegate(string msg);        /// <summary>
        /// TextBox委托实现,用于实现线程中访问窗体、组件等的线程安全性
        /// </summary>
        /// <param name="msg"></param>
        public void textboxset(string msg)
        {            if (textBox1 == null) return;            
        if (textBox1.InvokeRequired)
            {
                textbox_delegate dt = new textbox_delegate(textboxset);
                textBox1.Invoke(dt, new object[] { msg });
            }            
            else
            {                
            int strLen = msg.Length;                
            int step = 100;                
            while (strLen > step)
                {
                    textBox1.AppendText(msg.Substring(msg.Length - strLen, step));
                    strLen -= step;
                }
                textBox1.AppendText(msg.Substring(msg.Length - strLen, strLen));
            }
        }
Copy after login

Optimize Base64 encoding

                //计算Base64编码的字符串后部分有多少可以省略的字符
                int strLen = str.Length;
                string dyzf = str.Substring(strLen - 1, 1);                
                while ((dyzf == "A" || dyzf == "=") && strLen > 0)
                {
                    strLen -= 1;
                    dyzf = str.Substring(strLen - 1, 1);
                }                //组合完整的Data Url
                fullDataUrl = "<img src=\"data:image/" + ext + ";base64,"
                    + str.Substring(0, strLen)
                    + "\" width=\"" + img.Width + "\" height=\"" + img.Height + "\" />";                
                    //这里定义TextBox最多只显示20000个字符,多余的裁掉不显示了,不然性能太差。
                int showLen = 20000;                if (showLen > fullDataUrl.Length)
                {
                    showLen = fullDataUrl.Length;
                }
                textboxset(fullDataUrl.Substring(0, showLen));
Copy after login
        /// <summary>
        /// 将完整的Data Url复制到Windows剪贴板中。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_copy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(fullDataUrl);
        }
Copy after login
        /// <summary>
        /// 清空文本框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_clear_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            fullDataUrl = string.Empty;
        }
Copy after login

The above is the detailed content of Detailed introduction to the sample code of the second version of the Data Url generation tool C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles