以下是完整的解决方案:
<template>
<view>
<!-- 显示图片 -->
<image
:src="imageUrl"
mode="aspectFit"
style="width: 200px; height: 200px;"
></image>
<!-- 用于绘制的 canvas,可以设置 hidden -->
<canvas
canvas-id="myCanvas"
:style="{width: '200px', height: '200px'}"
hidden
></canvas>
<!-- 导出按钮 -->
<button @tap="exportImage">导出图片</button>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: '', // 你的图片地址
canvasWidth: 200,
canvasHeight: 200
}
},
methods: {
exportImage() {
const ctx = uni.createCanvasContext('myCanvas', this)
// 加载图片
uni.getImageInfo({
src: this.imageUrl,
success: (image) => {
// 计算缩放比例,保持原图比例
const ratio = Math.min(
this.canvasWidth / image.width,
this.canvasHeight / image.height
)
// 计算居中位置
const drawWidth = image.width * ratio
const drawHeight = image.height * ratio
const x = (this.canvasWidth - drawWidth) / 2
const y = (this.canvasHeight - drawHeight) / 2
// 在 canvas 上绘制图片
ctx.drawImage(
this.imageUrl,
x,
y,
drawWidth,
drawHeight
)
ctx.draw(false, () => {
// 导出图片
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
// res.tempFilePath 就是导出的图片路径
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: () => {
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
})
},
fail: (err) => {
console.error('导出失败', err)
}
}, this)
})
},
fail: (err) => {
console.error('获取图片信息失败', err)
}
})
}
}
}
</script> 主要步骤说明:
创建一个隐藏的 canvas 元素获取原图信息,计算缩放比例在 canvas 上绘制图片,保持原比例并居中将 canvas 导出为图片保存到相册注意事项:
需要在 manifest.json 中配置相册权限:
{
"app-plus": {
"modules": {
"OAuth": {}
},
"distribute": {
"android": {
"permissions": ["<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>"]
},
"ios": {
"photos": "保存图片到相册"
}
}
}
} 如果是 H5 端,canvas 的尺寸需要考虑设备像素比:
const pixelRatio = uni.getSystemInfoSync().pixelRatio this.canvasWidth = 200 * pixelRatio this.canvasHeight = 200 * pixelRatio
如果图片来自网络,确保图片已经加载完成再进行绘制。
网友回复
有没有免费让ai自动帮你接管操作电脑的mcp服务?
mcp为啥用Streamable HTTP 替代 HTTP + SSE?
scratchjr有没有开源的前端html网页版本源代码?
多模态大模型能否根据ui交互视频来来模仿写出前端交互动画效果ui代码?
如何用阿里云oss+函数计算fc+事件总线EventBridge+消息队列+数据库+redis缓存打造一个高并发弹性系统?
阿里云函数计算 FC如何在海外节点搭建一个代理网络?
ai studio中gemini build的代码如何发布到github pages等免费网页托管上 ?
如何在cursor、qoder、trae中使用Claude Skills功能?
有没有不用u盘就能重装系统的开源工具?
python如何固定摄像头实时计算停车场停车位剩余数量?


