uni-app 根据临时路径获取图片信息失败
uni-app 根据临时路径获取图片信息失败
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win7 | HBuilderX |
产品分类:uniapp/App
PC开发环境操作系统:Windows
PC开发环境操作系统版本号:win7
HBuilderX类型:正式
HBuilderX版本号:4.15
手机系统:Android
手机系统版本号:Android 9.0
手机厂商:华为
手机机型:P30
页面类型:vue
vue版本:vue2
打包方式:云端
项目创建方式:HBuilderX
### 操作步骤:
```cpp
//获取图片
uni.getImageInfo({
src: this.filepath,
complete: (imgInfo) => {
console.log(imgInfo)
},
})
//返回结果
{
"errMsg": "getImageInfo:fail 路径不存在",
"errCode": 14,
"code": 14
}
预期结果:
可以获取图片信息
实际结果:
提示路径不存在
bug描述:
生成临时路径后,退出APP,重新进入调用获取图片信息接口,会无法获取
更多关于uni-app 根据临时路径获取图片信息失败的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于uni-app 根据临时路径获取图片信息失败的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在 uni-app
中,如果你根据临时路径获取图片信息失败,可能是以下几个原因导致的。以下是一些常见的解决方法:
1. 临时路径问题
确保你使用的是正确的临时路径。临时路径通常是通过 uni.chooseImage
或 uni.uploadFile
等 API 获取的。临时路径的格式应该是 wxfile://
或 http://
开头。
如果你使用的是 uni.chooseImage
,可以这样获取临时路径:
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePaths = res.tempFilePaths;
// 使用 tempFilePaths[0] 作为临时路径
console.log(tempFilePaths[0]);
}
});
2. 图片信息获取 API 使用错误
如果你使用的是 uni.getImageInfo
来获取图片信息,确保你传递了正确的路径。
uni.getImageInfo({
src: tempFilePaths[0], // 确保这个是正确的临时路径
success: (res) => {
console.log(res.width); // 图片宽度
console.log(res.height); // 图片高度
console.log(res.path); // 图片路径
},
fail: (err) => {
console.error('获取图片信息失败', err);
}
});
3. 路径格式问题
在某些情况下,临时路径可能需要在不同平台下进行转换。例如,在微信小程序中,临时路径是 wxfile://
开头,而在 H5 中,路径可能是 blob:
或 http://
开头。
如果你需要跨平台使用,可以使用 uni.getImageInfo
来获取图片的本地路径:
uni.getImageInfo({
src: tempFilePaths[0],
success: (res) => {
const localPath = res.path; // 获取本地路径
console.log(localPath);
},
fail: (err) => {
console.error('获取图片信息失败', err);
}
});
4. 网络图片问题
如果你使用的是网络图片,确保图片 URL 是有效的,并且服务器没有限制跨域访问。
如果图片 URL 是跨域的,可能需要配置服务器允许跨域访问,或者在 uni-app
中使用 uni.downloadFile
先将图片下载到本地,然后再获取图片信息。
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
const tempFilePath = res.tempFilePath;
uni.getImageInfo({
src: tempFilePath,
success: (info) => {
console.log(info.width, info.height);
},
fail: (err) => {
console.error('获取图片信息失败', err);
}
});
},
fail: (err) => {
console.error('下载图片失败', err);
}
});
5. 权限问题
在某些平台上(如小程序),获取图片信息可能需要特定的权限。确保你在 manifest.json
或小程序配置文件中已经声明了相应的权限。
例如,在微信小程序中,你需要在 app.json
中声明 scope.writePhotosAlbum
权限。
6. 图片格式问题
确保图片格式是支持的格式(如 JPG、PNG 等)。某些特殊格式的图片可能无法被正确解析。
7. 调试与日志
如果以上方法都无法解决问题,建议你通过 console.log
或调试工具查看临时路径是否正确,以及 uni.getImageInfo
返回的错误信息,以便进一步排查问题。
uni.getImageInfo({
src: tempFilePaths[0],
success: (res) => {
console.log('图片信息:', res);
},
fail: (err) => {
console.error('获取图片信息失败:', err);
}
});