Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to copy an image

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to copy an image". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to copy an image".

There is something in the clipboard JS library that has written this 29.7k! After this article, I received two questions from my friend:

1.clipboard.js this library besides copying text, can you copy images?

The document.execCommand API that 2.clipboard.js this library depends on has been abandoned. What should I do in the future?

Next, this article will focus on the above two questions, but before we look at the first question, let's briefly introduce the clipboard.

Clipboard (English: clipboard), sometimes called clipboard, scrapbook, scrapbook. It is a software feature, usually provided by the operating system, that uses copy and paste operations to store data for a short period of time and transfer data between documents or applications. It is one of the most commonly used functions in the graphical user interface (GUI) environment. It is usually implemented as an anonymous, temporary data buffer and can be accessed by most or all programs in the environment using programming interfaces. Wikipedia

As we can see from the above description, the clipboard serves as a bridge, making it possible to transmit and share information between various applications. However, the only problem is that the clipboard can only retain one piece of data, and every time the new data comes in, the old one will be overwritten.

After learning about the clipboard? After the concept and function of clipboard.js, let's take a look at the first question: can the library copy images in addition to text?

1. Can clipboard.js copy the image?

Clipboard.js is a JS library for copying text to the clipboard. No Flash, no framework, only 3kb when gzipped compression is turned on.

(photo Source: https://clipboardjs.com/#example-text)

When you see the description "A modern approach to copy text to clipboard", do you already know the answer? So what is the actual situation? Let's check it out. There is something in this 29.7K clipboard JS library! In this article, Po introduced that when instantiating a ClipboardJS object, you can set the replication target through the target property of the options object:

/ / https://github.com/zenorocha/clipboard.js/blob/master/demo/function-target.html let clipboard = new ClipboardJS ('.btn', {target: function () {return document.querySelector ('div');}})

Taking advantage of this feature of clipboard.js, we can define the following HTML structure:

Hello, everyone. I'm Brother Po.

Copy

Then when you instantiate the ClipboardJS object, set the target for replication to be the # container element:

Const clipboard = new ClipboardJS (".btn", {target: function () {return document.querySelector ("# container");}})

After that, we click the copy button on the page, and the corresponding effect is shown below:

If you look at the image above, you can see that the image and text on the page have been copied. As for the text, everyone should be very clear. As for the image, what exactly is copied? How do we get the copied content? To solve this problem, we can take advantage of the onpaste attribute on the HTMLElement object or listen for paste events on the element.

Here we print the event object corresponding to the paste event by setting the onpaste property of the document object:

_ document.onpaste = function (e) {console.dir (e);}

When we click the copy button and then perform a paste operation on the page, the console prints the following:

As you can see from the figure above, there is a clipboardData property in the ClipboardEvent object that contains the data associated with the clipboard. After a detailed analysis of the clipboardData attribute, we find that the copied image and plain text are encapsulated as DataTransferItem objects.

To make it easier to analyze the DataTransferItem object, Po updated the onpaste property of the document object:

In the figure above, we can clearly see that there are kind and type attributes on the DataTransferItem object that represent the type of the data item (string or file) and the corresponding MIME type of the data. Using the getAsString method provided by the DataTransferItem object, we can get the data saved in the object:

I believe that after reading the above output results, the friends will know the answer to the first question very well. So if you want to copy an image, how do you do it? In fact, the answer to this question is the same as the answer to the second question raised by our partner. We can use Clipboard API to copy images and solve the problem that document.execCommand API has been abandoned.

Next, our goal is to achieve the function of copying images, because we want to make use of Clipboard API, so Brother Po will introduce the API first.

II. Brief introduction of Clipboard API

The Clipboard interface implements Clipboard API, which can provide read and write access to the system clipboard if the user is granted the appropriate permissions. In Web applications, Clipboard API can be used to implement cut, copy, and paste functions. The API is used instead of implementing clipboard operations through document.execCommand API.

In a real project, we don't need to create the Clipboard object manually, but we use navigator.clipboard to get the Clipboard object:

After getting the Clipboard object, we can use the API provided by the object to access the clipboard, such as:

Navigator.clipboard.readText () .then (clipText = > document.querySelector (".editor") .innerText = clipText)

The above code replaces the contents of the first element of the .editor class in HTML with the contents of the clipboard. If the clipboard is empty or does not contain any text, the contents of the element are emptied. This is because the readText method returns an empty string when the clipboard is empty or does not contain text.

Before moving on to Clipboard API, let's take a look at Navigator API: clipboard compatibility:

(photo Source: https://caniuse.com/mdn-api_navigator_clipboard)

Asynchronous clipboard API is a relatively new API, and browsers are still gradually implementing it. Due to potential security problems and technical complexity, most browsers are gradually integrating this API. For browser extensions, you can request clipboardRead and clipboardWrite permissions to use clipboard.readText () and clipboard.writeText ().

OK, let's show you how to use the API provided by the clipboard object to manipulate the clipboard. The following example runs in Chrome 87.0.4280.88.

Write data to the clipboard

3.1 writeText ()

The writeText method writes the specified string to the clipboard of the system, and when called, it returns a Promise object:

Copy the current page address async function copyPageUrl () {const text = new Blob ([location.href], {type: 'text/plain'}); try {await navigator.clipboard.write (new ClipboardItem ({"text/plain": text,}); console.log ("Page address has been copied to the clipboard") } catch (err) {console.error ("Page address copy failed:", err);}}

In the above code, we first create the Blob object through Blob API, then use the Blob object to construct the ClipboardItem object, and finally write the data to the clipboard through the write method. After describing how to write data to the clipboard, let's show how to read data from the clipboard.

Read data from the clipboard

4.1 readText ()

The readText method is used to read the text contents of the clipboard, and when called, a Promise object is returned:

Read the contents of the clipboard async function getClipboardContents () {try {const clipboardItems = await navigator.clipboard.read (); for (const clipboardItem of clipboardItems) {for (const type of clipboardItem.types) {const blob = await clipboardItem.getType (type); console.log ("read contents of the clipboard:", await blob.text ()) } catch (err) {console.error ("failed to read clipboard contents:", err);}}

For the above code, when the user clicks the read contents button on the clipboard, it starts to read the contents of the clipboard. So far, Brother Po has introduced all the four API involved in the clipboard object. Finally, let's take a look at how to copy the image.

Fifth, realize the function of copying image

In this final example, Brother Po will follow you step by step to achieve the core function of copying images. In addition to copying images, he will also support copying text. Before we look at the specific code, let's take a look at the actual effect:

In the page corresponding to the image above, we first click the copy button, and the image and text will be selected. After that, we click the paste button, and the console outputs the actual content read from the clipboard. Before analyzing the specific implementation, let's take a look at the corresponding page structure:

Hello, everyone. I'm Brother Po.

Paste

The structure of the above page is very simple. Next, we will analyze the implementation process of the above functions step by step.

5.1 request clipboard write permission

By default, write access to the clipboard is automatically granted to the currently active page. For security reasons, we take the initiative to ask the user for write permission to the clipboard:

Async function askWritePermission () {try {const {state} = await navigator.permissions.query ({name: "clipboard-write",}); return state = = "granted";} catch (error) {return false;}}

5.2 write images and plain text data to the clipboard

To write image data to the clipboard, we need to use the write method provided by the navigator.clipboard object. If we want to write image data, we need to obtain the Blob object corresponding to the image. Here, we can obtain the response object corresponding to the image from the network through fetch API and convert it into a Blob object. The specific implementation is as follows:

Async function createImageBlob (url) {const response = await fetch (url); return await response.blob ();}

For plain text, you can convert plain text to a Blob object simply by using the Blob API described earlier:

Function createTextBlob (text) {return new Blob ([text], {type: "text/plain"});}

After creating Blob objects for images and plain text, we can use them to create ClipboardItem objects, and then call the write method to write the data to the clipboard. The corresponding code is as follows:

Async function writeDataToClipboard () {if (askWritePermission ()) {if (navigator.clipboard & & navigator.clipboard.write) {const textBlob = createTextBlob ("Hello, I'm Brother Po"); const imageBlob = await createImageBlob ("http://cdn.semlinker.com/abao.png")" Try {const item = new ClipboardItem ({[textBlob.type]: textBlob, [imageBlob.type]: imageBlob,}); select (document.querySelector ("# container")); await navigator.clipboard.write ([item]); console.log ("text and image copied successfully") } catch (error) {console.error ("text and image copy failed", error);}

In the above code, a select method is used to achieve the selected effect, and the corresponding code is as follows:

Function select (element) {const selection = window.getSelection (); const range = document.createRange (); range.selectNodeContents (element); selection.removeAllRanges (); selection.addRange (range);}

Through the writeDataToClipboard method, we have written the image and plain text data to the clipboard. Let's use the read method provided by the navigator.clipboard object to read the data that has been written. If you need to read data from the clipboard, you need to ask the user for clipboard-read permission.

5.3 request clipboard read permission

Here we define an askReadPermission function to request the clipboard read permission from the user:

Async function askReadPermission () {try {const {state} = await navigator.permissions.query ({name: "clipboard-read",}); return state = = "granted";} catch (error) {return false;}}

When the askReadPermission method is called, the clipboard read permission is requested from the current user, and the corresponding effect is shown below:

5.4 read data that has been written on the clipboard

After creating the askReadPermission function, we can use the navigator.clipboard.read method described earlier to read the clipboard data:

Async function readDataFromClipboard () {if (askReadPermission ()) {if (navigator.clipboard & & navigator.clipboard.read) {try {const clipboardItems = await navigator.clipboard.read (); for (const clipboardItem of clipboardItems) {console.dir (clipboardItem); for (const type of clipboardItem.types) {const blob = await clipboardItem.getType (type) Console.log ("read clipboard contents:", await blob.text ());} catch (err) {console.error ("failed to read clipboard contents:", err);}

In fact, in addition to clicking the paste button, we can also read the data in the clipboard by listening for paste events. It is important to note that if the current browser does not support asynchronous Clipboard API, we can read the text data in the clipboard through the clipboardData.getData method:

Document.addEventListener ('paste', async (e) = > {e.preventDefault (); let text; if (navigator.clipboard) {text = await navigator.clipboard.readText ();} else {text = e.clipboardData.getData (' text/plain');} console.log ('obtained text data:', text);})

For image data, you can read it in the following ways:

Const IMAGE_MIME_REGEX = / ^ image\ / (p?jpeg | gif | png) $/ I; document.addEventListener ("paste", async (e) = > {e.preventDefault (); if (navigator.clipboard) {let clipboardItems = await navigator.clipboard.read (); for (const clipboardItem of clipboardItems) {for (const type of clipboardItem.types) {if (IMAGE_MIME_REGEX.test (type)) {const blob = await clipboardItem.getType (type)) LoadImage (blob); return;}} else {const items = e.clipboardData.items; for (let I = 0; I < items.length; items +) {if (IMAGE_MIME_REGEX.test (items [I] .type)) {loadImage (items [I]. GetAsFile ()); return })

The loadImage method in the above code is used to insert the copied image into the selected area of the current selection. The corresponding code is as follows:

Function loadImage (file) {const reader = new FileReader (); reader.onload = function (e) {let img = document.createElement ("img"); img.src = e.target.result; let range = window.getSelection (). GetRangeAt (0); range.deleteContents (); range.insertNode (img);}; reader.readAsDataURL (file) } Thank you for your reading, the above is the content of "how to copy an image". After the study of this article, I believe you have a deeper understanding of how to copy an image, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report