You've already forked guangan-mp
1.0.0
This commit is contained in:
76
common/image.js
Normal file
76
common/image.js
Normal file
@ -0,0 +1,76 @@
|
||||
// 读取图片 Base64 内容
|
||||
export function TaImageToBase64(file, maxw = 500) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (uni.compressImage) {
|
||||
uni.compressImage({
|
||||
src: file,
|
||||
quality: 80,
|
||||
width: maxw + "px",
|
||||
fail: err => reject(err),
|
||||
success: res =>
|
||||
readFileAsBase64(res.tempFilePath)
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
})
|
||||
} else {
|
||||
let img = new Image();
|
||||
(img.crossOrigin = "Anonymous"),
|
||||
(img.onload = () => {
|
||||
let c = document.createElement("canvas")
|
||||
let w = img.naturalWidth,
|
||||
h = img.naturalHeight;
|
||||
(c.width = Math.min(maxw, w)), (c.height = c.width * (h / w))
|
||||
// @ts-ignore
|
||||
c.getContext("2d").drawImage(img, 0, 0, c.width, c.height)
|
||||
resolve(c.toDataURL("image/jpeg", 0.8))
|
||||
}),
|
||||
(img.src = file),
|
||||
(img.onerror = () => reject(new Error("Failed to load image")))
|
||||
}
|
||||
})
|
||||
|
||||
// 读取文件为 base64 格式
|
||||
function readFileAsBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let rd = new plus.io.FileReader()
|
||||
rd.onerror = e => reject(e)
|
||||
rd.onloadend = v => resolve(v.target.result)
|
||||
// @ts-ignore
|
||||
rd.readAsDataURL(plus.io.convertLocalFileSystemURL(file))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 下载图片到本地
|
||||
export function TaImageDownload(imgUrl, name = "") {
|
||||
return new Promise((resolve, reject) => {
|
||||
// #ifdef H5
|
||||
const link = document.createElement("a")
|
||||
link.href = imgUrl
|
||||
link.download =
|
||||
name ||
|
||||
Math.random()
|
||||
.toString()
|
||||
.replace("0.", "img") + `.png`
|
||||
link.style.display = "none"
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
resolve(true)
|
||||
// #endif
|
||||
|
||||
// #ifndef H5
|
||||
uni.downloadFile({
|
||||
url: imgUrl,
|
||||
success: ret => {
|
||||
if (ret.statusCode === 200)
|
||||
uni.saveImageToPhotosAlbum({
|
||||
filePath: ret.tempFilePath,
|
||||
fail: err => TaToast.error("保存失败!", err).then(reject),
|
||||
success: () => TaToast.success("保存成功!").then(resolve)
|
||||
})
|
||||
}
|
||||
})
|
||||
// #endif
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user