首页 > 解决方案 > 如何使用输入标签 HTML 从用户那里获取的图像?

问题描述

我已经使用<input type='file'>了用户将放置任何图像的位置。然后我想使用该图像作为页面的背景。是否可以仅使用 HTML、CSS、JAVASCRIPT 来做到这一点?基本上我的想法是创建一个黑白图像转换器,我将从用户输入中获取图片,然后我将使用filter: grayscale()属性将其转换为黑白。请帮助我..我的代码如下 -

*{
  margin: 0;
  padding: 0;
}
/*Code for the image entered by user --
.image{
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 400px;
  height: 400px;
  background: url(); (set the image taken from user input)
  filter: grayscale(100%);
}
*/
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  <h1>Black and White Image Converter</h1>
  <label for="user-input">Attach the the image you want to convert : </label>
  <input type="file" name="user-input" id="user-input" placeholder="Attach any image.."><!--Use this image-->
  <div class="image"><!--I want to display that image as background of this div-->
</body>
</html>

任何帮助表示赞赏..

标签: javascripthtmlcss

解决方案


function changeImage(input) {
  var file_reader;
  if (input.files && input.files[0]) {
    file_reader = new FileReader();
    file_reader.onload = function(e) {
      document.getElementById("image").setAttribute('src', e.target.result);
    }

    file_reader.readAsDataURL(input.files[0]);
  }
}

<input type="file" name="user-input" id="user-input" placeholder="Attach any image.." onchange="changeImage()" /><!--Use this image-->
<img id="image" />

试试这个它可能会有所帮助!


推荐阅读