javascripts读取图片
时间: 2024-06-23 13:02:19 浏览: 260
在JavaScript中,读取图片通常涉及到操作文件系统或通过网络请求。这里主要介绍两种常见的方式:
1. **从本地文件读取**(使用FileReader API):
- 使用`FileReader`对象,你可以选择用户选择的图片文件:
```javascript
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = e.target.files;
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement('img');
img.src = e.target.result;
document.body.appendChild(img);
};
reader.readAsDataURL(file); // 读取为Data URL
});
```
2. **从服务器读取**(使用XMLHttpRequest或Fetch API):
- 如果图片在服务器上,你可以使用AJAX请求获取图片内容:
```javascript
var imgElement = document.createElement('img');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'path/to/image.jpg', true);
xhr.responseType = 'blob'; // 对于二进制数据
xhr.onload = function() {
if (xhr.status === 200) {
var urlCreator = window.URL || window.webkitURL; // Browsers may use different APIs for URLs
imgElement.src = urlCreator.createObjectURL(xhr.response);
}
};
xhr.send();
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)