图片转Base64代码实例

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了将图片转换为Base64格式功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style type="text/css">
html {
  font-family: "microsoft yahei";
  overflow: hidden;
}
html {
  height: 100%;
  padding: 0;
  margin: 0;
}
a {
  text-decoration: none;
  outline: none;
}
.title {
  color: #ddd;
  text-shadow: 2px 2px 5px #000;
  padding: 80px 0px 0px 100px;
}
.main, .img_main {
  float: left;
  background-color: rgba(255,255,255,.7);
  border-radius: 4px;
  padding: 20px;
  margin: 0 3px;
}
.main {
  width: 40%;
  margin-left: 100px;
}
.img_main {
  max-width: 40%;
}
.preview {
  width: 100%;
}
.select-file {
  border: 1px solid #9B59B6;
  position: relative;
}
.select-file:after {
  content: '';
  display: block;
  clear: both;
}
.select-file-title, .select-file-btn {
  float: left;
  line-height: 30px;
  height: 30px;
}
.select-file-title {
  width: 80%;
}
.select-file-btn {
  width: 20%;
  background-color: #8E44AD;
  text-align: center;
  color: #fff;
  transition: background-color .5s;
}
.select-file-btn:hover {
  background-color: #1ABC9C;
}
.base64-text {
  background-color: transparent;
  height: 300px;
  width: calc(100% - 6px);
  resize: none;
  overflow: auto;
  border: 1px solid #9B59B6;
  margin-top: 10px;
  word-break: break-all;
}
</style>
</head>
<body>
<h1 class="title">图片转Base64</h1>
<div class="main">
  <div class="control">
    <div class="select-file">
      <div class="select-file-title"></div>
      <a href="javascript:;" class="select-file-btn">选择文件</a>
    </div>
  </div>
  <div class="control">
    <textarea class="base64-text" readonly></textarea>
  </div>
</div>
<div class="img_main">
  <img src="" class="preview" />
</div>
<script type="text/javascript">
var inputFile = document.createElement('input');
inputFile.type = 'file';
var selectFile = document.querySelector('.select-file');
var base64Text = document.querySelector('.base64-text');
var preview = document.querySelector('.preview');
 
var reader = new FileReader();
reader.onload = function() {
  base64Text.innerText = this.result;
  preview.src = this.result;
};
 
inputFile.addEventListener('change', function() {
  selectFile.querySelector('.select-file-title').innerHTML = this.value;
  if (this.files.length == 0) {
    base64Text.innerText = '';
    return;
  }
  var file = inputFile.files[0];
  base64Text.placeholder = '';
  if (!(/^image/.test(file.type))) {
    base64Text.placeholder = '不是图片文件';
    return;
  }
  reader.readAsDataURL(file);
});
 
selectFile.addEventListener('click', function() {
  inputFile.click();
});
</script>
</body>
</html>

图片转Base64代码实例,这样的场景在实际项目中还是用的比较多的,关于图片转Base64代码实例就介绍到这了。

图片转Base64代码实例属于前端实例代码,有关更多实例代码大家可以查看

图片转Base64代码实例

回复

我来回复
  • 暂无回复内容