以下是完整的解决方案:
<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
如果图片来自网络,确保图片已经加载完成再进行绘制。
网友回复
为啥所有的照片分辨率提升工具都会修改照片上的图案细节?
js如何在浏览器中将webm视频的声音分离为单独音频?
微信小程序如何播放第三方域名url的mp4视频?
ai多模态大模型能实时识别视频中的手语为文字吗?
如何远程调试别人的chrome浏览器获取调试信息?
为啥js打开新网页window.open设置窗口宽高无效?
浏览器中js的navigator.mediaDevices.getDisplayMedia屏幕录像无法录制SpeechSynthesisUtterance产生的说话声音?
js中mediaRecorder如何录制window.speechSynthesis声音音频并下载?
python如何直接获取抖音短视频的音频文件url?
js在浏览器中如何使用MediaStream与MediaRecorder实现声音音频多轨道混流?