laitimes

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

author:IT technology sharing community
C# Practice: Introduction to Image Clarity Enhancement and Case Practice

1. Introduction to image clarity enhancement

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

Based on Tencent Cloud's deep learning and other artificial intelligence technologies, it eliminates the noise caused by lossy compression, improves the image blur caused by the use of filters, out-of-focus shooting, etc., and makes the edges and details of the image clearer and more natural.

Second, the development process

First, log in to the Tencent Cloud platform to activate the image processing service on the official website: https://cloud.tencent.com/product/imageprocess

Apply for a development key

Download the SDK for the programming language

Develop tools to create a project

Reference to Tencent Image Processing Library

Write code based on your business

3. Request parameters

● Region:资源地域,必填,表示操作的资源所属的地域,比如 ap-shanghai ap-beijing ap-shenzhen 等。

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

● ImageUrl: the URL parameter of the image. Image formats: PNG, JPG, JPEG. Image size: The downloaded image should not exceed 4M after Base64 encoding. The image download time should not exceed 3 seconds.

● ImageBase64: supports PNG, JPG, JPEG, BMP, and does not support GIF images. Base64-encoded image. The maximum is not more than 4M. If the ImageUrl field exists at the same time, the ImageUrl field is preferred. Note: Images need to be Base64 encoded, and the encoding header needs to be removed.

4. Description of output parameters

● EnhancedImage:增强后图片的base64编码。 示例值:/9j/4AAQSkZJRgABAQAAAQABA...

● RequestId: A unique request ID that is returned for each request. When troubleshooting the anomaly, you need to provide the RequestId of the request.

5. Development Practices

Here we use SDK+C# language to write a WinForm program. Here's how:

First, create a WinForm console program EnhanceImageDemo and select NetFramework 4.5.2 as the framework.

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

5.1 安装依赖库TencentCloudSDK.Tiia

From the command line

dotnet add package TencentCloudSDK.Tiia
           

Install it by using the Nuget package manager

Open the nuget package manager, search for TencentCloudSDK.Tiia, and install the latest stable version 3.0.957.

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

5.2 Added Tencent API call configuration items

Add it directly in the app.config file, and the full content is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
		<appSettings>
			<!--SecretId-->
			<add key="SecretId" value="xxxxxx"/>
			<!--SecretKey-->
			<add key="SecretKey" value="xxxxxx"/>
			<!--地区选择ap-shanghai ap-beijing ap-shenzhen 等-->
			<add key="Region" value="ap-shanghai"/>
			<!--图片输出目录-->
			<add key="OutPath" value="D:\Image\"/>
</appSettings>
</configuration>
           

Note: The developer needs to apply for the development key and fill in the configuration file.

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

5.3 Code

It mainly implements the network image URL to call the image enhancement processing method to generate Base64 strings, and then converts them into png images, and directly calls the default open image tool of the operating system to directly open the image.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Tiia.V20190529;
using TencentCloud.Tiia.V20190529.Models;
using System.Configuration;
namespace EnhanceImageDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 图片增强方法
        /// </summary>
        private void EnhanceImage()
        {
            string url = textBox1.Text.Trim();
            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                MessageBox.Show("请输入正确的图片URL");
            }
            else
            {
                // 调用腾讯云接口的参数说明
                string secretId = ConfigurationManager.AppSettings["SecretId"];
                string secretKey = ConfigurationManager.AppSettings["SecretKey"];
                string region = ConfigurationManager.AppSettings["Region"];
                try
                {
                    // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,需注意密钥对的保密             
                    // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
                    Credential cred = new Credential
                    {
                        SecretId = secretId,
                        SecretKey = secretKey
                    };
                    // 实例化一个client选项,可选的,没有特殊需求可以跳过
                    ClientProfile clientProfile = new ClientProfile();
                    // 实例化一个http选项,可选的,没有特殊需求可以跳过
                    HttpProfile httpProfile = new HttpProfile();
                    httpProfile.Endpoint = ("tiia.tencentcloudapi.com");
                    clientProfile.HttpProfile = httpProfile;

                    // 实例化要请求产品的client对象,clientProfile是可选的
                    TiiaClient client = new TiiaClient(cred, region, clientProfile);
                    // 实例化一个请求对象,每个接口都会对应一个request对象 传递参数,支持网络图片和图片经过Base64编码的内容
                    EnhanceImageRequest req = new EnhanceImageRequest();
                    //图片URL地址参数。图片格式:PNG、JPG、JPEG。 图片大小:所下载图片经Base64编码后不超过4M。图片下载时间不超过3秒。
                    req.ImageUrl = url;
                    //ImageBase64 参数 支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。图片经过Base64编码的内容。最大不超过4M。与ImageUrl同时存在时优先使用ImageUrl字段。注意:图片需要Base64编码,并且要去掉编码头部。
                    req.ImageBase64 = "无";
                    // 返回的resp是一个EnhanceImageResponse的实例,与请求对象对应
                    EnhanceImageResponse resp = client.EnhanceImageSync(req);
                     convertToImage(resp.EnhancedImage);             
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
        }

        /// <summary>
        /// base64字符串转换为png
        /// </summary>
        /// <param name="base64String"></param>
        private void convertToImage(string base64String)        
        {
            // 把Base64 字符串解码为字节数组
            byte[] imageBytes = Convert.FromBase64String(base64String);
            // 配置文件图片图片输出目录
            string path = ConfigurationManager.AppSettings["OutPath"];
            string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
            // 将字节数组保存为图片文件
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                Image image = Image.FromStream(ms);
                // 保存图片
                image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                // 调用系统默认程序打开图片文件
                Process.Start(fileName);
            }
        }
        /// <summary>
        /// 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            EnhanceImage();
        }
    }
}

           

5.4 Operational Effects

View the debugging data of the API that is successfully invoked

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

The page runs in the form, mainly the image network address input and conversion buttons

C# Practice: Introduction to Image Clarity Enhancement and Case Practice

The following is the result of the successful conversion:

C# Practice: Introduction to Image Clarity Enhancement and Case Practice