Step 3: Implement Document Scanning in JavaScript

With the environment ready, the next step is to implement the relevant functions in JavaScript.

Get Devices

Enumerate the available scanners.

const ScannerType = {    // TWAIN scanner type, represented by the value 0x10    TWAINSCANNER: 0x10,    // WIA scanner type, represented by the value 0x20    WIASCANNER: 0x20,    // 64-bit TWAIN scanner type, represented by the value 0x40    TWAINX64SCANNER: 0x40,    // ICA scanner type, represented by the value 0x80    ICASCANNER: 0x80,    // SANE scanner type, represented by the value 0x100    SANESCANNER: 0x100,    // eSCL scanner type, represented by the value 0x200    ESCLSCANNER: 0x200,    // WiFi Direct scanner type, represented by the value 0x400    WIFIDIRECTSCANNER: 0x400,    // WIA-TWAIN scanner type, represented by the value 0x800    WIATWAINSCANNER: 0x800};let queryDevicesButton = document.getElementById(\\\"query-devices-button\\\");queryDevicesButton.onclick = async () => {    let scannerType = ScannerType.TWAINSCANNER | ScannerType.TWAINX64SCANNER;    let devices = await getDevices(host, scannerType);    let select = document.getElementById(\\\"sources\\\");    select.innerHTML = \\'\\';    for (let i = 0; i < devices.length; i  ) {        let device = devices[i];        let option = document.createElement(\\\"option\\\");        option.text = device[\\'name\\'];        option.value = JSON.stringify(device);        select.add(option);    };}async function getDevices(host, scannerType) {    devices = [];    let url = host   \\'/DWTAPI/Scanners\\'    if (scannerType != null) {        url  = \\'?type=\\'   scannerType;    }    try {        let response = await fetch(url);        if (response.ok) {            let devices = await response.json();            return devices;        }    } catch (error) {        console.log(error);    }    return [];}

Explanation

Acquire Image

Scan documents from the selected scanner by specifying the pixel type, resolution, and other settings.

let scanButton = document.getElementById(\\\"scan-button\\\");scanButton.onclick = async () => {    let select = document.getElementById(\\\"sources\\\");    let device = select.value;    if (device == null || device.length == 0) {        alert(\\'Please select a scanner.\\');        return;    }    let inputText = document.getElementById(\\\"inputText\\\").value;    let license = inputText.trim();    if (license == null || license.length == 0) {        alert(\\'Please input a valid license key.\\');    }    let parameters = {        license: license,        device: JSON.parse(device)[\\'device\\'],    };    let showUICheck = document.getElementById(\\\"showUICheckId\\\");    let pixelTypeSelect = document.getElementById(\\\"pixelTypeSelectId\\\");    let resolutionSelect = document.getElementById(\\\"resolutionSelectId\\\");    let adfCheck = document.getElementById(\\\"adfCheckId\\\");    let duplexCheck = document.getElementById(\\\"duplexCheckId\\\");    parameters.config = {        IfShowUI: showUICheck.checked,        PixelType: pixelTypeSelect.selectedIndex,        Resolution: parseInt(resolutionSelect.value),        IfFeederEnabled: adfCheck.checked,        IfDuplexEnabled: duplexCheck.checked,    };    let jobId = await scanDocument(host, parameters);    let images = await getImages(host, jobId);    for (let i = 0; i < images.length; i  ) {        let url = images[i];        let img = document.getElementById(\\'document-image\\');        img.src = url;        data.unshift(url);        let option = document.createElement(\\\"option\\\");        option.selected = true;        option.text = url;        option.value = url;        let thumbnails = document.getElementById(\\\"thumb-box\\\");        let newImage = document.createElement(\\'img\\');        newImage.setAttribute(\\'src\\', url);        if (thumbnails != null) {            thumbnails.insertBefore(newImage, thumbnails.firstChild);            newImage.addEventListener(\\'click\\', e => {                if (e != null && e.target != null) {                    let target = e.target;                    img.src = target.src;                    selectedThumbnail = target;                }            });        }        selectedThumbnail = newImage;    }}async function scanDocument(host, parameters, timeout = 30) {    let url = host   \\'/DWTAPI/ScanJobs?timeout=\\'   timeout;    try {        let response = await fetch(url, {            method: \\'POST\\',            headers: {                \\'Content-Type\\': \\'application/json\\'            },            body: JSON.stringify(parameters)        });        if (response.ok) {            let jobId = await response.text();            return jobId;        }        else {            return \\'\\';        }    } catch (error) {        alert(error);        return \\'\\';    }}async function getImages(host, jobId) {    let images = [];    let url = host   \\'/DWTAPI/ScanJobs/\\'   jobId   \\'/NextDocument\\';    while (true) {        try {            let response = await fetch(url);            if (response.status == 200) {                const arrayBuffer = await response.arrayBuffer();                const blob = new Blob([arrayBuffer], { type: response.type });                const imageUrl = URL.createObjectURL(blob);                images.push(imageUrl);            }            else {                break;            }        } catch (error) {            console.error(\\'No more images.\\');            break;        }    }    return images;}

Explanation

Rotate Image

Rotate the scanned image by -90 or 90 degrees.

let rotateLeftButton = document.getElementById(\\\"rotate-left-button\\\");rotateLeftButton.onclick = () => {    let img = document.getElementById(\\'document-image\\');    img.src = rotateImage(\\'document-image\\', -90);    selectedThumbnail.src = img.src;}let rotateRightButton = document.getElementById(\\\"rotate-right-button\\\");rotateRightButton.onclick = () => {    let img = document.getElementById(\\'document-image\\');    img.src = rotateImage(\\'document-image\\', 90);    selectedThumbnail.src = img.src;}    function rotateImage (imageId, angle) {    const image = document.getElementById(imageId);    const canvas = document.createElement(\\'canvas\\');    const context = canvas.getContext(\\'2d\\');    const imageWidth = image.naturalWidth;    const imageHeight = image.naturalHeight;    // Calculate the new rotation    let rotation = 0;    rotation = (rotation   angle) % 360;    // Adjust canvas size for rotation    if (rotation === 90 || rotation === -270 || rotation === 270) {        canvas.width = imageHeight;        canvas.height = imageWidth;    } else if (rotation === 180 || rotation === -180) {        canvas.width = imageWidth;        canvas.height = imageHeight;    } else if (rotation === 270 || rotation === -90) {        canvas.width = imageHeight;        canvas.height = imageWidth;    } else {        canvas.width = imageWidth;        canvas.height = imageHeight;    }    // Clear the canvas    context.clearRect(0, 0, canvas.width, canvas.height);    // Draw the rotated image on the canvas    context.save();    if (rotation === 90 || rotation === -270) {        context.translate(canvas.width, 0);        context.rotate(90 * Math.PI / 180);    } else if (rotation === 180 || rotation === -180) {        context.translate(canvas.width, canvas.height);        context.rotate(180 * Math.PI / 180);    } else if (rotation === 270 || rotation === -90) {        context.translate(0, canvas.height);        context.rotate(270 * Math.PI / 180);    }    context.drawImage(image, 0, 0);    context.restore();    return canvas.toDataURL();}

Delete Image

Delete all scanned images, including the main image and thumbnails, and reset the data array.

let deleteButton = document.getElementById(\\\"delete-button\\\");deleteButton.onclick = async () => {    let img = document.getElementById(\\'document-image\\');    img.src = \\'images/default.png\\';    data = [];    let thumbnails = document.getElementById(\\\"thumb-box\\\");    thumbnails.innerHTML = \\'\\';}

Step 4: Interop Between C# and JavaScript for Saving Images

Saving images directly in JavaScript is restricted due to security concerns. Therefore, we need to interoperate between C# and JavaScript to accomplish this task.

  1. Create a JavaScript function to convert the scanned image to a base64 string.

    function getBase64Image() {    var img = document.getElementById(\\'document-image\\');    var canvas = document.createElement(\\'canvas\\');    canvas.width = img.naturalWidth;    canvas.height = img.naturalHeight;    var ctx = canvas.getContext(\\'2d\\');    ctx.drawImage(img, 0, 0);    var dataURL = canvas.toDataURL(\\'image/png\\');     var base64 = dataURL.split(\\',\\')[1];     return base64;}
  2. When clicking the save button, set window.location.href to trigger the OnWebViewNavigated event handler of the WebView control.

    let saveButton = document.getElementById(\\\"save-button\\\");saveButton.onclick = async () => {    window.location.href = \\'invoke://CallCSharpFunction\\';    }
  3. In the OnWebViewNavigated event handler, call EvaluateJavaScriptAsync to retrieve the base64 image data from JavaScript and save it to a file.

    private async void OnWebViewNavigated(object sender, WebNavigatingEventArgs e){    if (e.Url.StartsWith(\\\"invoke://callcsharpfunction\\\"))    {        var base64String = await WebView.EvaluateJavaScriptAsync(\\\"getBase64Image()\\\");        CallCSharpFunction(base64String);    }}private void CallCSharpFunction(string base64String){    if (!string.IsNullOrEmpty(base64String))    {        try        {            byte[] imageBytes = Convert.FromBase64String(base64String);            var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), GenerateFilename());            File.WriteAllBytes(filePath, imageBytes);            DisplayAlert(\\\"Success\\\", \\\"Image saved to: \\\"   filePath, \\\"OK\\\");        }        catch (Exception ex)        {            DisplayAlert(\\\"Error\\\", ex.Message, \\\"OK\\\");        }    }    else    {        DisplayAlert(\\\"Failure\\\", \\\"No image data found\\\", \\\"OK\\\");    }}private string GenerateFilename(){    DateTime now = DateTime.Now;    string timestamp = now.ToString(\\\"yyyyMMdd_HHmmss\\\");    return $\\\"image_{timestamp}.png\\\";}

Note: Do not pass the base64 string directly to the C# function via window.location.href, as the string may be too long and cause an error. Instead, return the base64 string when calling EvaluateJavaScriptAsync from the C# function.

Step 5: Run the .NET MAUI Document Scanner Application

Press F5 in Visual Studio or Visual Studio Code to run the .NET document scanner application on Windows or macOS.

\\\"Switching

Source Code

https://github.com/yushulx/dotnet-twain-wia-sane-scanner/tree/main/examples/MauiWebView

","image":"http://www.luping.net/uploads/20240801/172251253066ab7492458d1.png","datePublished":"2024-08-01T19:42:09+08:00","dateModified":"2024-08-01T19:42:09+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 從 .NET MAUI Blazor 切換到 WebView 控制項進行文件掃描

從 .NET MAUI Blazor 切換到 WebView 控制項進行文件掃描

發佈於2024-08-01
瀏覽:324

In .NET MAUI development, both BlazorWebView and WebView are used to display web content, but they serve different purposes and are designed for different scenarios. The BlazorWebView is specifically designed to host Blazor components in a .NET MAUI application, allowing you to reuse Blazor components and share code between web and native applications. The WebView is a general-purpose control for displaying web content, including web pages, HTML strings, and local HTML files. In this article, we will explore how to transition a .NET MAUI Blazor document scanner application to a .NET MAUI application using the WebView control, implementing the document scanning logic in JavaScript and HTML, and enabling interoperation between C# and JavaScript to scan documents and save images.

Prerequisites

  1. Install Dynamsoft Service: This service is necessary for communicating with TWAIN, SANE, ICA, ESCL, and WIA scanners on Windows and macOS.
    • Windows: Dynamsoft-Service-Setup.msi
    • macOS: Dynamsoft-Service-Setup.pkg
  2. Request a Free Trial License: Obtain a 30-day free trial license for Dynamic Web TWAIN to get started.

Step 1: Create a New .NET MAUI Project with WebView Control

  1. In Visual Studio or Visual Studio Code, create a new .NET MAUI project.
  2. Open the MainPage.xaml file and replace the existing code with the following XAML to add a WebView control:

    
    
    
        
            
                
    
            
        
    
    
    
  3. Open the MainPage.xaml.cs file and add the following code to set the source of the WebView and handle the Navigating event:

    namespace MauiWebView
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
                LoadHtmlFile();
            }
    
            private void LoadHtmlFile()
            {
                WebView.Source = "index.html";
    
            }
    
            private async void OnWebViewNavigated(object sender, WebNavigatingEventArgs e)
            {
                if (e.Url.StartsWith("invoke://callcsharpfunction"))
                {
                    // TODO: Implement interop between C# and JavaScript
                }
            }
        }
    
    }
    
    

    Exaplanation:

    • The LoadHtmlFile method sets the Source property of the WebView control to load the index.html file.
    • The OnWebViewNavigated method is triggered when the WebView navigates to a new URL. It checks if the URL starts with invoke://callcsharpfunction and, if so, allows for C# and JavaScript interop.

Step 2: Load Static HTML, JavaScript, and CSS Files into the WebView Control

In a .NET MAUI project, you can load static HTML, JavaScript, and CSS files located in the Resources/Raw folder into the WebView. Ensure that the MauiAsset build action is included in the .csproj file:


    

Switching from .NET MAUI Blazor to WebView Control for Document Scanning

We create a similar UI layout as the previous Blazor document scanner application in the index.html file.




    
    

    Dynamsoft RESTful API Example
    



    

Document Scanner


Acquire Image

Image Tools

從 .NET MAUI Blazor 切換到 WebView 控制項進行文件掃描

Step 3: Implement Document Scanning in JavaScript

With the environment ready, the next step is to implement the relevant functions in JavaScript.

Get Devices

Enumerate the available scanners.

const ScannerType = {
    // TWAIN scanner type, represented by the value 0x10
    TWAINSCANNER: 0x10,

    // WIA scanner type, represented by the value 0x20
    WIASCANNER: 0x20,

    // 64-bit TWAIN scanner type, represented by the value 0x40
    TWAINX64SCANNER: 0x40,

    // ICA scanner type, represented by the value 0x80
    ICASCANNER: 0x80,

    // SANE scanner type, represented by the value 0x100
    SANESCANNER: 0x100,

    // eSCL scanner type, represented by the value 0x200
    ESCLSCANNER: 0x200,

    // WiFi Direct scanner type, represented by the value 0x400
    WIFIDIRECTSCANNER: 0x400,

    // WIA-TWAIN scanner type, represented by the value 0x800
    WIATWAINSCANNER: 0x800
};

let queryDevicesButton = document.getElementById("query-devices-button");
queryDevicesButton.onclick = async () => {
    let scannerType = ScannerType.TWAINSCANNER | ScannerType.TWAINX64SCANNER;
    let devices = await getDevices(host, scannerType);
    let select = document.getElementById("sources");
    select.innerHTML = '';
    for (let i = 0; i 



Explanation

  • The getDevices function sends a GET request to the RESTful API endpoint /DWTAPI/Scanners to fetch the available scanners. The scanner type is specified by the scannerType parameter.

Acquire Image

Scan documents from the selected scanner by specifying the pixel type, resolution, and other settings.

let scanButton = document.getElementById("scan-button");
scanButton.onclick = async () => {
    let select = document.getElementById("sources");
    let device = select.value;

    if (device == null || device.length == 0) {
        alert('Please select a scanner.');
        return;
    }

    let inputText = document.getElementById("inputText").value;
    let license = inputText.trim();

    if (license == null || license.length == 0) {
        alert('Please input a valid license key.');
    }

    let parameters = {
        license: license,
        device: JSON.parse(device)['device'],
    };

    let showUICheck = document.getElementById("showUICheckId");

    let pixelTypeSelect = document.getElementById("pixelTypeSelectId");

    let resolutionSelect = document.getElementById("resolutionSelectId");

    let adfCheck = document.getElementById("adfCheckId");

    let duplexCheck = document.getElementById("duplexCheckId");

    parameters.config = {
        IfShowUI: showUICheck.checked,
        PixelType: pixelTypeSelect.selectedIndex,
        Resolution: parseInt(resolutionSelect.value),
        IfFeederEnabled: adfCheck.checked,
        IfDuplexEnabled: duplexCheck.checked,
    };


    let jobId = await scanDocument(host, parameters);
    let images = await getImages(host, jobId);

    for (let i = 0; i  {
                if (e != null && e.target != null) {
                    let target = e.target;
                    img.src = target.src;
                    selectedThumbnail = target;
                }
            });
        }

        selectedThumbnail = newImage;
    }

}

async function scanDocument(host, parameters, timeout = 30) {
    let url = host   '/DWTAPI/ScanJobs?timeout='   timeout;

    try {
        let response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(parameters)
        });

        if (response.ok) {
            let jobId = await response.text();
            return jobId;
        }
        else {
            return '';
        }
    } catch (error) {
        alert(error);
        return '';
    }
}

async function getImages(host, jobId) {
    let images = [];
    let url = host   '/DWTAPI/ScanJobs/'   jobId   '/NextDocument';

    while (true) {
        try {

            let response = await fetch(url);

            if (response.status == 200) {
                const arrayBuffer = await response.arrayBuffer();
                const blob = new Blob([arrayBuffer], { type: response.type });
                const imageUrl = URL.createObjectURL(blob);

                images.push(imageUrl);
            }
            else {
                break;
            }

        } catch (error) {
            console.error('No more images.');
            break;
        }
    }

    return images;
}

Explanation

  • The scanDocument function sends a POST request to the RESTful API endpoint /DWTAPI/ScanJobs to start a scanning job. The parameters include the license key, device name, and scanning settings.
  • The getImages function sends a GET request to the RESTful API endpoint /DWTAPI/ScanJobs/{jobId}/NextDocument to fetch scanned images. The images are stored in a blob object and displayed in the image display area.

Rotate Image

Rotate the scanned image by -90 or 90 degrees.

let rotateLeftButton = document.getElementById("rotate-left-button");
rotateLeftButton.onclick = () => {
    let img = document.getElementById('document-image');
    img.src = rotateImage('document-image', -90);
    selectedThumbnail.src = img.src;
}

let rotateRightButton = document.getElementById("rotate-right-button");
rotateRightButton.onclick = () => {
    let img = document.getElementById('document-image');
    img.src = rotateImage('document-image', 90);
    selectedThumbnail.src = img.src;
}

    function rotateImage (imageId, angle) {
    const image = document.getElementById(imageId);
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const imageWidth = image.naturalWidth;
    const imageHeight = image.naturalHeight;

    // Calculate the new rotation
    let rotation = 0;
    rotation = (rotation   angle) % 360;

    // Adjust canvas size for rotation
    if (rotation === 90 || rotation === -270 || rotation === 270) {
        canvas.width = imageHeight;
        canvas.height = imageWidth;
    } else if (rotation === 180 || rotation === -180) {
        canvas.width = imageWidth;
        canvas.height = imageHeight;
    } else if (rotation === 270 || rotation === -90) {
        canvas.width = imageHeight;
        canvas.height = imageWidth;
    } else {
        canvas.width = imageWidth;
        canvas.height = imageHeight;
    }

    // Clear the canvas
    context.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the rotated image on the canvas
    context.save();
    if (rotation === 90 || rotation === -270) {
        context.translate(canvas.width, 0);
        context.rotate(90 * Math.PI / 180);
    } else if (rotation === 180 || rotation === -180) {
        context.translate(canvas.width, canvas.height);
        context.rotate(180 * Math.PI / 180);
    } else if (rotation === 270 || rotation === -90) {
        context.translate(0, canvas.height);
        context.rotate(270 * Math.PI / 180);
    }
    context.drawImage(image, 0, 0);
    context.restore();

    return canvas.toDataURL();
}

Delete Image

Delete all scanned images, including the main image and thumbnails, and reset the data array.

let deleteButton = document.getElementById("delete-button");
deleteButton.onclick = async () => {
    let img = document.getElementById('document-image');
    img.src = 'images/default.png';
    data = [];
    let thumbnails = document.getElementById("thumb-box");
    thumbnails.innerHTML = '';
}

Step 4: Interop Between C# and JavaScript for Saving Images

Saving images directly in JavaScript is restricted due to security concerns. Therefore, we need to interoperate between C# and JavaScript to accomplish this task.

  1. Create a JavaScript function to convert the scanned image to a base64 string.

    function getBase64Image() {
        var img = document.getElementById('document-image');
        var canvas = document.createElement('canvas');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
    
        var dataURL = canvas.toDataURL('image/png'); 
        var base64 = dataURL.split(',')[1]; 
        return base64;
    }
    
  2. When clicking the save button, set window.location.href to trigger the OnWebViewNavigated event handler of the WebView control.

    let saveButton = document.getElementById("save-button");
    saveButton.onclick = async () => {
        window.location.href = 'invoke://CallCSharpFunction';    
    }
    
  3. In the OnWebViewNavigated event handler, call EvaluateJavaScriptAsync to retrieve the base64 image data from JavaScript and save it to a file.

    private async void OnWebViewNavigated(object sender, WebNavigatingEventArgs e)
    {
        if (e.Url.StartsWith("invoke://callcsharpfunction"))
        {
            var base64String = await WebView.EvaluateJavaScriptAsync("getBase64Image()");
            CallCSharpFunction(base64String);
        }
    }
    
    private void CallCSharpFunction(string base64String)
    {
        if (!string.IsNullOrEmpty(base64String))
        {
    
            try
            {
                byte[] imageBytes = Convert.FromBase64String(base64String);
    
                var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), GenerateFilename());
                File.WriteAllBytes(filePath, imageBytes);
                DisplayAlert("Success", "Image saved to: "   filePath, "OK");
    
            }
            catch (Exception ex)
            {
                DisplayAlert("Error", ex.Message, "OK");
            }
        }
        else
        {
            DisplayAlert("Failure", "No image data found", "OK");
        }
    }
    
    private string GenerateFilename()
    {
        DateTime now = DateTime.Now;
        string timestamp = now.ToString("yyyyMMdd_HHmmss");
        return $"image_{timestamp}.png";
    }
    

Note: Do not pass the base64 string directly to the C# function via window.location.href, as the string may be too long and cause an error. Instead, return the base64 string when calling EvaluateJavaScriptAsync from the C# function.

Step 5: Run the .NET MAUI Document Scanner Application

Press F5 in Visual Studio or Visual Studio Code to run the .NET document scanner application on Windows or macOS.

Switching from .NET MAUI Blazor to WebView Control for Document Scanning

Source Code

https://github.com/yushulx/dotnet-twain-wia-sane-scanner/tree/main/examples/MauiWebView

版本聲明 本文轉載於:https://dev.to/yushulx/switching-from-net-maui-blazor-to-webview-control-for-document-scanning-31lp?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-25
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSocke...
    程式設計 發佈於2024-12-25
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-25
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-25
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-25
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-25
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內...
    程式設計 發佈於2024-12-25
  • 如何將 Pandas DataFrame 字串條目分解(拆分)為單獨的行?
    如何將 Pandas DataFrame 字串條目分解(拆分)為單獨的行?
    將Pandas DataFrame 字串條目分解(拆分)為單獨的行在Pandas 中,一個常見的要求是將逗號分隔的值拆分為文字字串列並為每個條目建立一個新行。這可以透過各種方法來實現。 使用Series.explode()或DataFrame.explode()對於Pandas版本0.25.0以上版...
    程式設計 發佈於2024-12-25
  • Java中如何使用Selenium WebDriver高效率上傳檔案?
    Java中如何使用Selenium WebDriver高效率上傳檔案?
    在Java 中使用Selenium WebDriver 上傳文件:詳細指南將文件上傳到Web 應用程式是軟體測試期間的一項常見任務。 Selenium WebDriver 是一種流行的自動化框架,它提供了一種使用 Java 程式碼上傳檔案的簡單方法。然而,重要的是要明白,在 Selenium 中上傳...
    程式設計 發佈於2024-12-24
  • 使用 GNU Emacs 進行 C 語言開發
    使用 GNU Emacs 進行 C 語言開發
    Emacs is designed with programming in mind, it supports languages like C, Python, and Lisp natively, offering advanced features such as syntax highli...
    程式設計 發佈於2024-12-24
  • 如何在 PHP 中列印單引號內的變數?
    如何在 PHP 中列印單引號內的變數?
    無法直接回顯帶有單引號的變數需要在單引號字串中列印變數?直接這樣做是不可能的。 如何在單引號內列印變數:方法1:使用串聯追加 為此,請使用點運算子將變數連接到字串上:echo 'I love my ' . $variable . '.';此方法將變數追加到字串中。 方法 2:使用雙引號或者,在字串並...
    程式設計 發佈於2024-12-24
  • std::vector 與普通數組:何時效能真正重要?
    std::vector 與普通數組:何時效能真正重要?
    std::vector 與普通數組:性能評估雖然人們普遍認為std::vector 的操作與數組類似,但最近的測試對這一概念提出了挑戰。在本文中,我們將研究 std::vector 和普通數組之間的效能差異,並闡明根本原因。 為了進行測試,實施了一個基準測試,其中涉及重複建立和修改大型陣列像素物件。...
    程式設計 發佈於2024-12-24
  • 為什麼雙精確度的小數位數比宣傳的 15 位多?
    為什麼雙精確度的小數位數比宣傳的 15 位多?
    雙精度和小數位精度在電腦程式設計中,雙精度資料型態通常被假定為具有 15 位小數的近似精度。但是,某些數字表示形式(例如 1.0/7.0)在變數內部表示時似乎具有更高的精確度。本文將探討為什麼會發生這種情況,以及為什麼精確度通常被描述為小數點後 15 位左右。 內部表示IEEE 雙精度數有 53 個...
    程式設計 發佈於2024-12-24
  • 箭頭函數中的隱式回傳與明確傳回:何時需要大括號?
    箭頭函數中的隱式回傳與明確傳回:何時需要大括號?
    箭頭函數中的花括號:隱式與明確返回箭頭函數可以用兩種方式編寫:帶或不帶花括號。當大括號不存在時,函數體被認為是“簡潔體”,並且隱式傳回其中的最後一個表達式。 帶有簡潔體的隱式回傳In不帶大括號的範例:state.map(one => oneTodo(one, action))The函數立即傳回...
    程式設計 發佈於2024-12-24
  • 為什麼使用「transform:scale()」後我的文字在 Chrome 中變得模糊?
    為什麼使用「transform:scale()」後我的文字在 Chrome 中變得模糊?
    變換後Chrome 中的文字模糊:scale()在最近的Chrome 更新中,出現了一個特殊問題,即使用CSS 轉換呈現的文字:scale() 屬性顯得模糊。使用以下特定程式碼時已觀察到此問題:@-webkit-keyframes bounceIn { 0% { opacity: 0; ...
    程式設計 發佈於2024-12-24

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3