+
88
-

回答

以下是完整的解决方案:

<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

如果图片来自网络,确保图片已经加载完成再进行绘制。

网友回复

我知道答案,我要回答