以下是完整的解决方案:
<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
如果图片来自网络,确保图片已经加载完成再进行绘制。
网友回复
DLNA与UPnP的区别和不同?
苏超自建抢票app,通过先预约再抽签化解高并发抢票?
python如何让给电脑在局域网中伪装成电视接收手机的投屏图片视频播放?
如何结合python+js如何自己的视频编码与加密播放直播?
python如何在电脑上通过局域网将本地视频或m3u8视频投屏电视播放?
腾讯视频爱奇艺优酷vip电影电视剧视频如何通过python绕过vip收费直接观看?
有没有可免费观看全球电视台直播m3u8地址url的合集?
有没有实现观影自由的免vip影视苹果 CMS V10 API的可用url?
python如何实时检测电脑usb插入检测报警?
如何判断真人操作的鼠标移动直线轨迹与机器操作的轨迹?