|
@@ -0,0 +1,65 @@
|
|
|
|
+<!DOCTYPE html>
|
|
|
|
+<html>
|
|
|
|
+<head>
|
|
|
|
+ <meta charset="UTF-8">
|
|
|
|
+ <title>webp</title>
|
|
|
|
+ <style>
|
|
|
|
+ #image-display {
|
|
|
|
+ max-width: 100%;
|
|
|
|
+ max-height: 100%;
|
|
|
|
+ border: 1px solid gray;
|
|
|
|
+ }
|
|
|
|
+ </style>
|
|
|
|
+</head>
|
|
|
|
+<body>
|
|
|
|
+<h1>粘贴图片并展示</h1>
|
|
|
|
+<p>右键粘贴图片,本地图片或网络图片地址都可以,将被压缩为webp格式并展示</p>
|
|
|
|
+<div id="image-container">
|
|
|
|
+ <img id="image-display" src="" alt="Image Display">
|
|
|
|
+</div>
|
|
|
|
+<script>
|
|
|
|
+ const imageDisplay = document.getElementById("image-display");
|
|
|
|
+
|
|
|
|
+ // 监听粘贴事件
|
|
|
|
+ document.addEventListener("paste", (event) => {
|
|
|
|
+ // 获取粘贴板数据
|
|
|
|
+ const items = event.clipboardData.items;
|
|
|
|
+ if (!items) {
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // 查找图片数据
|
|
|
|
+ for (let i = 0; i < items.length; i++) {
|
|
|
|
+ if (items[i].type.indexOf("image") !== -1) {
|
|
|
|
+ // 获取图片文件或URL
|
|
|
|
+ const blob = items[i].getAsFile();
|
|
|
|
+ const imageUrl = URL.createObjectURL(blob);
|
|
|
|
+
|
|
|
|
+ // 将图片展示
|
|
|
|
+ imageDisplay.src = imageUrl;
|
|
|
|
+
|
|
|
|
+ // 压缩为webp格式
|
|
|
|
+ const image = new Image();
|
|
|
|
+ image.onload = () => {
|
|
|
|
+ const canvas = document.createElement("canvas");
|
|
|
|
+ canvas.width = image.naturalWidth;
|
|
|
|
+ canvas.height = image.naturalHeight;
|
|
|
|
+ const context = canvas.getContext("2d");
|
|
|
|
+ context.drawImage(image, 0, 0);
|
|
|
|
+ canvas.toBlob((webpBlob) => {
|
|
|
|
+ // 将压缩后的webp图片展示在页面上
|
|
|
|
+ const webpUrl = URL.createObjectURL(webpBlob);
|
|
|
|
+ imageDisplay.src = webpUrl;
|
|
|
|
+
|
|
|
|
+ }, "image/webp", 0.8);
|
|
|
|
+ };
|
|
|
|
+ image.src = imageUrl;
|
|
|
|
+
|
|
|
|
+ // 防止页面跳转
|
|
|
|
+ event.preventDefault();
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ });
|
|
|
|
+</script>
|
|
|
|
+</body>
|
|
|
|
+</html>
|