uniapp 安卓原生截图保存到相册跟api服务器 canvas实现 plus.nativeObj.Bitmap实现

复制代码
// 截图plus.nativeObj.Bitma

// const handleScreenshot = () => {
//   try {
//     const timestamp = new Date().getTime()
//     const filePath = `_doc/screenshot_${timestamp}.png`
//     const currentPages = getCurrentPages()
//     const currentPage = currentPages[currentPages.length - 1]
//     const webview = currentPage.$getAppWebview() // 获取当前页面 webview
//     const bitmap = new plus.nativeObj.Bitmap('screenshot_' + timestamp)
//     webview.draw(
//       bitmap,
//       () => {
//         // 保存到本地 _doc/
//         bitmap.save(
//           filePath,
//           { overwrite: true, format: 'png' },
//           (res) => {
//             console.log('截图保存成功', res.target)

//             // 保存到手机相册
//             plus.gallery.save(res.target, (galleryRes) => {
//               console.log('已保存到相册:', galleryRes)
//               uni.showToast({ title: '已保存到相册', icon: 'success' })
//             }, (galleryErr) => {
//               console.error('保存相册失败', galleryErr)
//             })

//             // 上传到服务器
//             uni.uploadFile({
//               url: 'http://xxxxxx:8090/photo/upload',
//               filePath: res.target,
//               name: 'file',
//               success: (uploadRes) => uni.showToast({ title: '已到媒体库', icon: 'success' }) ,
//               fail: (err) => console.error('上传失败', err)
//             })

//             // 释放 bitmap 资源
//             bitmap.clear()
//           },
//           (err) => {
//             console.error('保存 _doc/ 失败', err)
//             bitmap.clear()
//           }
//         )
//       },
//       (err) => {
//         console.error('截图 draw 失败', err)
//         bitmap.clear()
//       }
//     )
//   } catch (error) {
//     console.error('截图异常', error)
//   }
// }


// 截图 canvas
// const handleScreenshot = () => {
//   try {
//     const timestamp = new Date().getTime()
//     const canvasId = 'drawCanvas'          // 你的 canvas-id
//     const filePath = `_doc/screenshot_${timestamp}.png`

//     // 使用 uniApp 官方 API 生成临时文件
//     uni.canvasToTempFilePath({
//       canvasId,
//       fileType: 'png',
//       success: (res) => {
//         console.log('canvas 截图成功', res.tempFilePath)

//         // 保存到本地 _doc/
//         const tempPath = res.tempFilePath

//         // 保存到手机相册
//         plus.gallery.save(tempPath, 
//           () => {
//             console.log('已保存到相册:', tempPath)
//           }, 
//           (err) => {
//             console.error('保存到相册失败', err)
//           }
//         )

//         // 上传到服务器
//         uni.uploadFile({
//           url: 'http://xxxxx/photo/upload',
//           filePath: tempPath,
//           name: 'file',
//           success: (uploadRes) => console.log('上传成功', uploadRes),
//           fail: (err) => console.error('上传失败', err)
//         })
//       },
//       fail: (err) => {
//         console.error('canvas 截图失败', err)
//       }
//     })
//   } catch (error) {
//     console.error('截图异常', error)
//   }
// }

两个绘制跟界面合成一张图截图-实现

复制代码
<template>
  <view >  
          <view @click="handleScreenshot">截图</view>
  <canvas canvas-id="canvasMerge" width="750" height="517"
      style="width:750rpx;height:517rpx;position:absolute;left:-9999px;top:-9999px;"></canvas>
  </view>
</template>


let imgPath1 = ref('')
let imgPath2 = ref('')
const screenshotBitmap = async () => {
  return new Promise((resolve, reject) => {
    try {
      const timestamp = new Date().getTime()
      const filePath = `_doc/screenshot_bitmap_${timestamp}.png`
      const currentPages = getCurrentPages()
      const currentPage = currentPages[currentPages.length - 1]
      const webview = currentPage.$getAppWebview()
      const bitmap = new plus.nativeObj.Bitmap('screenshot_' + timestamp)

      webview.draw(
        bitmap,
        () => {
          bitmap.save(
            filePath,
            { overwrite: true, format: 'png' },
            (res) => {
              imgPath1.value = res.target
              bitmap.clear()
              resolve(res.target)
            },
            (err) => {
              bitmap.clear()
              reject(err)
            }
          )
        },
        (err) => {
          bitmap.clear()
          reject(err)
        }
      )
    } catch (error) {
      reject(error)
    }
  })
}
// ------------------------
// 截图 canvas
// ------------------------
const screenshotCanvas = async (canvasId = 'drawCanvas') => {
  return new Promise((resolve, reject) => {
    try {
      const timestamp = new Date().getTime()
      plus.io.resolveLocalFileSystemURL('_doc/', (docEntry) => {
        const fileName = `screenshot_canvas_${timestamp}.png`
        uni.canvasToTempFilePath({
          canvasId,
          fileType: 'png',
          success: (res) => {
            plus.io.resolveLocalFileSystemURL(res.tempFilePath, (entry) => {
              entry.copyTo(
                docEntry,
                fileName,
                (newEntry) => {
                  imgPath2.value = newEntry.toLocalURL()
                  resolve(newEntry.toLocalURL())
                },
                (err) => reject(err)
              )
            }, (err) => reject(err))
          },
          fail: (err) => reject(err)
        })
      }, (err) => reject(err))
    } catch (error) {
      reject(error)
    }
  })
}
// 合成截图
const mergeScreenshots = async (path1, path2) => {
  const systemInfo = uni.getSystemInfoSync()
  const canvasWidthPx =systemInfo.screenWidth 
  const canvasHeightPx = systemInfo.screenHeight 

  return new Promise((resolve, reject) => {
    try {
      const ctx = uni.createCanvasContext('canvasMerge')
      ctx.clearRect(0, 0, canvasWidthPx, canvasHeightPx)
      ctx.drawImage(path1, 0, 0, canvasWidthPx, canvasHeightPx)
      ctx.drawImage(path2, 0, 0, canvasWidthPx, canvasHeightPx)

      ctx.draw(false, () => {
        const timestamp = new Date().getTime()
        const fileName = `merge_${timestamp}.png`

        uni.canvasToTempFilePath({
          canvasId: 'canvasMerge',
          fileType: 'png',
          success: (res) => {
            plus.io.resolveLocalFileSystemURL('_doc/', (docEntry) => {
              plus.io.resolveLocalFileSystemURL(res.tempFilePath, (entry) => {
                entry.copyTo(
                  docEntry,
                  fileName,
                  (newEntry) => resolve(newEntry.toLocalURL()),
                  (err) => reject(err)
                )
              }, (err) => reject(err))
            }, (err) => reject(err))
          },
          fail: (err) => reject(err)
        })
      })
    } catch (error) {
      reject(error)
    }
  })
}
// ------------------------
// 点击按钮执行
// ------------------------
const handleScreenshot = async () => {
  try {
    const path1 = await screenshotBitmap()
    const path2 = await screenshotCanvas('drawCanvas')
    const mergedPath = await mergeScreenshots(path1, path2)
    // 保存到相册
    plus.gallery.save(
      mergedPath,
      () => uni.showToast({ title: '已保存到相册', icon: 'success' }),
      (err) => console.error('保存相册失败', err)
    )

    // 上传到服务器
    uni.uploadFile({
      url: 'http://xxxx:8090/photo/upload',
      filePath: mergedPath,
      name: 'file',
      success: (res) => console.log('上传成功', res),
      fail: (err) => console.error('上传失败', err)
    })
  } catch (error) {
    console.error('截图/合成异常', error)
  }
}
相关推荐
心中无石马26 分钟前
uniapp引入tailwindcss4.x
前端·css·uni-app
fix一个write十个42 分钟前
【uniApp开发】微信小程序 web-view 内嵌 H5 跳转支付踩坑实录
微信小程序·uni-app
饭小猿人2 小时前
Android 腾讯X5WebView如何禁止系统自带剪切板和自定义剪切板视图
android·java
_李小白2 小时前
【android opencv学习笔记】Day 8: remap(像素位置重映射)
android·opencv·学习
美狐美颜SDK开放平台2 小时前
多场景美颜SDK解决方案:直播APP(iOS/安卓)开发接入详解
android·人工智能·ios·音视频·美颜sdk·第三方美颜sdk·短视频美颜sdk
嗷o嗷o3 小时前
Android BLE 里,MTU、分包和长数据发送到底该怎么处理
android
wuxianda10304 小时前
苹果App上架4.3a被拒解决方案汇报总结
ios·uni-app·objective-c·cocoa·苹果上架·4.3a
Gary Studio4 小时前
Android AIDL HAL工程结构示例
android
y = xⁿ5 小时前
MySQL八股知识合集
android·mysql·adb