首页 > 编程语言 >国庆头像制作小程序相关代码

国庆头像制作小程序相关代码

时间:2024-09-28 14:49:14浏览次数:12  
标签:function console res 代码 头像 国庆 data imageUrl wx

↓↓ 点击下方搜索开始制作您的专属头像 ↓↓

发现-》搜一搜-》最美易飞证件照制作

图片

图片

国庆头像自定义头像制作、微信头像直接获取制作小程序源码

index.wxml文件代码

// pages/userPhoto/userPhoto.js//获取应用实例const app = getApp()import {  Router} from '../../utils/router.js'import constant from './constant.js'import config from '../../config/index';import RewardedAds from '../../utils/rewarded-ads';
const instanceRewardedAds = new RewardedAds(config.rewardAdsSaveHead);Router({  /**   * 页面的初始数据   */  data: {        isiPhoneX: false,    userImage: 'https://qiniu.bigerfe.com/default_avator.jpeg',    new_userImage: '',    new_showuserImage: false,    isLead: false,    userInfo: {},    hasUserInfo: true,    canIUse: wx.canIUse('button.open-type.getUserInfo'),    photo_bj_num: constant.Head_TIP_PIC,    photo_select_idx: 0,    indexAdCode: config.indexAdCode,    indexPageAdCode: config.indexPageAdCode  },
  // 插屏广告  initAdShow() {    // 在页面中定义插屏广告    let interstitialAd = null
    // 在页面onLoad回调事件中创建插屏广告实例    if (wx.createInterstitialAd) {      interstitialAd = wx.createInterstitialAd({        adUnitId: this.data.indexPageAdCode      })      interstitialAd.onLoad(() => { })      interstitialAd.onError((err) => { })      interstitialAd.onClose(() => { })    }
    // 在适合的场景显示插屏广告    if (interstitialAd) {      interstitialAd.show().catch((err) => {        console.error(err)      })    }  },
  /**   * 生命周期函数--监听页面加载   */  onl oad: function () {    const initAvator = getApp().globalData?.initAvator;    if (initAvator) {      this.setData({        userImage: getApp().globalData?.initAvator,      });    }    this.initAdShow();    //初始化激励性广告    instanceRewardedAds.adInit();  },  onChooseAvatar(e) {    const {      avatarUrl    } = e.detail;    console.log(avatarUrl)    this.setUserCusPhoto(avatarUrl);  },  /**   * 用户点击获取图片   */  tapWxAvator: function () {    this.getUSerWechatInfo_Photo();  },
  tapOpenPhoto() {    this.getUSerMobile_Photo();  },
  /**   * 下载用户微信头像   */  setUserWeCahtPhoto: function (url) {    let that = this    console.log('url', url);    getApp().globalData.initAvator = url;    wx.downloadFile({      url: that.headimgHD(url),      success: function (res) {        if (res.statusCode === 200) {          that.drawImg(res.tempFilePath, that.data.photo_select_idx);        }      }    })  },
  /**   * 下载截图页面返回的图片   */  setUserCusPhoto: function (url) {    getApp().globalData.initAvator = url;    this.drawImg(url, this.data.photo_select_idx);  },
  //从自定义图片页面返回调用的方法,需要增加延迟,否则会出现神器的问题  setFromCusPhotoBack: function (url) {    wx.showLoading({      title: '处理中...',    })    setTimeout(() => {      this.setUserCusPhoto(url);    }, 1500);  },
  /**   * 获取用户微信头像   */  getUSerWechatInfo_Photo: function () {    let that = this    wx.getUserProfile({      desc: '不需要再次上传',      success: res => {        app.globalData.userInfo = res.userInfo        that.setData({          userInfo: res.userInfo,          hasUserInfo: true        })        that.setUserWeCahtPhoto(app.globalData.userInfo.avatarUrl);      },      fail: error => {        console.log('fail', error);      },      complete: data => {        console.log('complete', data);      }    })    //}  },
  /**   * 打开用户相册   */  getUSerMobile_Photo: function () {    let that = this    // let index = e.currentTarget.dataset.index    wx.chooseImage({      count: 1,      sizeType: ['original', 'compressed'],      sourceType: ['album'],      success(res) {        // tempFilePath可以作为img标签的src属性显示图片        let tempFilePaths = res.tempFilePaths[0];        wx.showLoading({          title: '安全检测中...',        });        wx.uploadFile({          url: getApp().globalData.appurl+'sec/checkimg',          formData: {              appid: "wx738e184b4b0280d6"          },          filePath: tempFilePaths,          name: "file",           header: {              "content-type": "multipart/form-data"          },          success: function (res) {            wx.hideLoading()              if (res.data == "true") {                  wx.showModal({                      title: '提示',                      content: "请勿上传违规违法图片",                      success: () => {}                  })              }              const data = JSON.parse(res.data)              console.log(tempFilePaths)              if (data.code == 200 && data.resultStatus == false) {                  wx.showToast({                      title: "图片检测完成",                      icon: "none",                      duration: 1500                  });
                  wx.navigateTo({                    url: `/pages/avatarUpload/upload/upload?src=${tempFilePaths}`                  });
                //   t.setData({                //     bncolor:"#fff",                //     imageSrc: tempFilePaths                 // }), t.loadImage();              } else {                  wx.showModal({                      title: '提示',                      content: data.data,                      success: () => {
                      }                  })              }          },          fail: function (err) {              wx.showToast({                  title: "上传失败",                  icon: "none",                  duration: 2000              })          },          complete: function (result) {              console.log(result.errMsg)          }      })              },      fail: function (res) {        console.log(res.errMsg)      }    });  },  /**   * 重置画布   */  editClick: function () {    this.setData({      hasUserInfo: false,      userImage: '',      new_userImage: '',      new_showuserImage: false    })  },
  /**   * 获取高清微信头像   */  headimgHD: function (imageUrl) {    imageUrl = imageUrl.split('/');    if (imageUrl[imageUrl.length - 1] &&      (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {      imageUrl[imageUrl.length - 1] = 0;    }    imageUrl = imageUrl.join('/');    return imageUrl;  },  saveloadFile: function () {    let thisT = this;    console.log("1,老铁没毛病" + thisT.data.isLead);    if (!thisT.data.new_userImage) {      wx.showModal({        content: '没有图片可保存~',        showCancel: false,        confirmText: '明白了',      })      return    } else {      if (!thisT.data.isLead) {        wx.showModal({          content: '即将展示广告,看完广告即可下载',          showCancel: true,          confirmText: '确认',          success(res) {            if (res.confirm) {              console.log("222点击确定,老铁没毛病");              //展示激励性广告              if (!instanceRewardedAds.isEnded) {                console.log("333点击确定,老铁没毛病");                instanceRewardedAds.showAd();                thisT.data.isLead = true;                console.log("2,老铁没毛病" + thisT.data.isLead);                return;              }            }          }        })      } else {        wx.showLoading({          title: '保存中...'        })        let that = this        wx.saveImageToPhotosAlbum({          filePath: that.data.new_userImage,          success(res) {            wx.hideLoading();            wx.showModal({              content: '图片已保存到相册了~',              showCancel: false,              confirmText: '保存成功',              success(res) {                if (res.confirm) {                  console.log("点击确定,老铁没毛病");                 // instanceRewardedAds.resetAd(); //下次还需要继续看广告                  // thisT.data.isLead=false;                }              }            })          },          fail() {            wx.hideLoading();            instanceRewardedAds.resetAd(); //下次还需要继续看广告            thisT.data.isLead=false;          }        })      }    }  },  bigimg: function (e) {    if (this.data.userImage) {      this.setData({        photo_select_idx: e.currentTarget.dataset.item      });      this.drawImg(this.data.userImage, this.data.photo_select_idx);    }  },  //绘图  drawImg(headImg, index) {    let that = this    wx.showLoading({      title: '头像生成中...',    })
    let promiseHead = new Promise((resolve, reject) => {      wx.getImageInfo({        src: headImg,        success(res) {          resolve(res)        },        fail(e) {          reject("调用失败head");          wx.hideLoading()        }      })    })    Promise.all([promiseHead]).then(promiseRes => {      let num = 1024      let width_userIcon = num      let x_userIcon = (num - (num)) / 2      let frameImgUrl = that.data.photo_bj_num[index];      const query = wx.createSelectorQuery()      query.select('#genimg')        .fields({          node: true,          size: true        })        .exec((res) => {          const canvas = res[0].node          const ctx = canvas.getContext('2d');          // 初始化画布大小          const dpr = wx.getWindowInfo().pixelRatio;          canvas.width = 1024 * dpr          canvas.height = 1024 * dpr          ctx.scale(dpr, dpr)          const bg1 = canvas.createImage();          const bg2 = canvas.createImage();          bg1.src = promiseRes[0].path;          bg1.onload = () => {            ctx.drawImage(bg1, x_userIcon, x_userIcon, width_userIcon, width_userIcon);            bg2.onload = () => {              ctx.drawImage(bg2, 0, 0, num, num);            }            bg2.src = frameImgUrl;          }          setTimeout(() => {            // 第一个参数为false,表示先清空画布再绘制            wx.canvasToTempFilePath({              x: 0,              y: 0,              width: num,              height: num,              destWidth: num,              destHeight: num,              canvas,              quality: 1,              success(res) {                that.setData({                  new_userImage: res.tempFilePath,                  new_showuserImage: true,                  userImage: headImg                })                wx.hideLoading()              },              fail(res) {                console.log("绘图错误:" + JSON.stringify(res));                wx.hideLoading();              }            }, that);          }, 1000);        })    }).catch(e => console.log(e));  }})

index.wxss文件代码

/* pages/userPhoto/userPhoto.wxss */
.isIPx{  padding-bottom: 64rpx !important;}.background{  width: 100%;  min-height: 1000px;  position:absolute;   background-size:100% 100%;  z-index: -1;}.logo{  display: flex;  justify-content: center;  align-items: center;}.hearder{  text-align: center;  overflow-wrap: break-word;  display: flex;  flex-direction: row;  justify-content: center;  align-items: center;}.hearder_logo{  margin-top: 5rpx;  height: 250rpx;}.hearder_title{  display: block;  margin-left: 40rpx;  margin-right: 40rpx;  color: white;}.hearder-mainView{  background-color: white;  display: flex;  align-items: center;  justify-content: center;    height: 320rpx;  width: 320rpx;  border-radius: 5px;}.add-photo{  width: 140rpx;  height: 140rpx;}.user-photo{  width: 100%;  height: 100%;}.user-photo-wechat{  width: 300rpx;  height: 300rpx;}.hearder-button{  display: flex;  align-items: flex-start;  flex-direction: column;}.hearder-button button{  margin: 20rpx;  width: 320rpx;  height: 70rpx; line-height: 70rpx;  background-color: rgb(224, 224, 28);  color: #000;}/* 将画布隐藏起来 */canvas {  position: fixed;  top: 0;  left: 1024px;}
.bjphoto_view{  margin: 20rpx;  padding: 10rpx;  background-color: white;}
.photo_bj{  width: 100%;  height:100%;   white-space: nowrap; }.photo_bj_img{  margin-left: 10rpx;  width: 120rpx;  height: 120rpx;  border: solid 1rpx #f0f0f0;  border-radius: 15rpx;}.photo_bj_br{  border: solid 4rpx red;}.avatar-wrapper{  width: 200rpx;}
/* userPhoto.wxss */.notice-wrap {  position: fixed;  bottom: 0;  left: 0;  width: 100%;  background-color: #00000080; /* 半透明背景 */  color: #fff; /* 白色文字 */  padding: 10rpx 0;  z-index: 999; /* 确保在最上层 */}
.notice-scroll {  height: 60rpx; /* 滚动区域的高度 */  overflow-y: auto; /* 允许垂直滚动 */}
.notice-text {  margin: 0 auto;  text-align: center;}
.notice-text-content {  font-size: 12px; /* 更小的字体 */  color: #00ff00; /* 绿色文字 */  padding: 10rpx;}

index.js代码如下

// pages/userPhoto/userPhoto.js//获取应用实例const app = getApp()import {  Router} from '../../utils/router.js'import constant from './constant.js'import config from '../../config/index';import RewardedAds from '../../utils/rewarded-ads';
const instanceRewardedAds = new RewardedAds(config.rewardAdsSaveHead);Router({  /**   * 页面的初始数据   */  data: {        isiPhoneX: false,    userImage: 'https://qiniu.bigerfe.com/default_avator.jpeg',    new_userImage: '',    new_showuserImage: false,    isLead: false,    userInfo: {},    hasUserInfo: true,    canIUse: wx.canIUse('button.open-type.getUserInfo'),    photo_bj_num: constant.Head_TIP_PIC,    photo_select_idx: 0,    indexAdCode: config.indexAdCode,    indexPageAdCode: config.indexPageAdCode  },
  // 插屏广告  initAdShow() {    // 在页面中定义插屏广告    let interstitialAd = null
    // 在页面onLoad回调事件中创建插屏广告实例    if (wx.createInterstitialAd) {      interstitialAd = wx.createInterstitialAd({        adUnitId: this.data.indexPageAdCode      })      interstitialAd.onLoad(() => { })      interstitialAd.onError((err) => { })      interstitialAd.onClose(() => { })    }
    // 在适合的场景显示插屏广告    if (interstitialAd) {      interstitialAd.show().catch((err) => {        console.error(err)      })    }  },
  /**   * 生命周期函数--监听页面加载   */  onl oad: function () {    const initAvator = getApp().globalData?.initAvator;    if (initAvator) {      this.setData({        userImage: getApp().globalData?.initAvator,      });    }    this.initAdShow();    //初始化激励性广告    instanceRewardedAds.adInit();  },  onChooseAvatar(e) {    const {      avatarUrl    } = e.detail;    console.log(avatarUrl)    this.setUserCusPhoto(avatarUrl);  },  /**   * 用户点击获取图片   */  tapWxAvator: function () {    this.getUSerWechatInfo_Photo();  },
  tapOpenPhoto() {    this.getUSerMobile_Photo();  },
  /**   * 下载用户微信头像   */  setUserWeCahtPhoto: function (url) {    let that = this    console.log('url', url);    getApp().globalData.initAvator = url;    wx.downloadFile({      url: that.headimgHD(url),      success: function (res) {        if (res.statusCode === 200) {          that.drawImg(res.tempFilePath, that.data.photo_select_idx);        }      }    })  },
  /**   * 下载截图页面返回的图片   */  setUserCusPhoto: function (url) {    getApp().globalData.initAvator = url;    this.drawImg(url, this.data.photo_select_idx);  },
  //从自定义图片页面返回调用的方法,需要增加延迟,否则会出现神器的问题  setFromCusPhotoBack: function (url) {    wx.showLoading({      title: '处理中...',    })    setTimeout(() => {      this.setUserCusPhoto(url);    }, 1500);  },
  /**   * 获取用户微信头像   */  getUSerWechatInfo_Photo: function () {    let that = this    wx.getUserProfile({      desc: '不需要再次上传',      success: res => {        app.globalData.userInfo = res.userInfo        that.setData({          userInfo: res.userInfo,          hasUserInfo: true        })        that.setUserWeCahtPhoto(app.globalData.userInfo.avatarUrl);      },      fail: error => {        console.log('fail', error);      },      complete: data => {        console.log('complete', data);      }    })    //}  },
  /**   * 打开用户相册   */  getUSerMobile_Photo: function () {    let that = this    // let index = e.currentTarget.dataset.index    wx.chooseImage({      count: 1,      sizeType: ['original', 'compressed'],      sourceType: ['album'],      success(res) {        // tempFilePath可以作为img标签的src属性显示图片        let tempFilePaths = res.tempFilePaths[0];        wx.showLoading({          title: '安全检测中...',        });        wx.uploadFile({          url: getApp().globalData.appurl+'sec/checkimg',          formData: {              appid: "wx738e184b4b0280d6"          },          filePath: tempFilePaths,          name: "file",           header: {              "content-type": "multipart/form-data"          },          success: function (res) {            wx.hideLoading()              if (res.data == "true") {                  wx.showModal({                      title: '提示',                      content: "请勿上传违规违法图片",                      success: () => {}                  })              }              const data = JSON.parse(res.data)              console.log(tempFilePaths)              if (data.code == 200 && data.resultStatus == false) {                  wx.showToast({                      title: "图片检测完成",                      icon: "none",                      duration: 1500                  });
                  wx.navigateTo({                    url: `/pages/avatarUpload/upload/upload?src=${tempFilePaths}`                  });
                //   t.setData({                //     bncolor:"#fff",                //     imageSrc: tempFilePaths                 // }), t.loadImage();              } else {                  wx.showModal({                      title: '提示',                      content: data.data,                      success: () => {
                      }                  })              }          },          fail: function (err) {              wx.showToast({                  title: "上传失败",                  icon: "none",                  duration: 2000              })          },          complete: function (result) {              console.log(result.errMsg)          }      })              },      fail: function (res) {        console.log(res.errMsg)      }    });  },  /**   * 重置画布   */  editClick: function () {    this.setData({      hasUserInfo: false,      userImage: '',      new_userImage: '',      new_showuserImage: false    })  },
  /**   * 获取高清微信头像   */  headimgHD: function (imageUrl) {    imageUrl = imageUrl.split('/');    if (imageUrl[imageUrl.length - 1] &&      (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {      imageUrl[imageUrl.length - 1] = 0;    }    imageUrl = imageUrl.join('/');    return imageUrl;  },  saveloadFile: function () {    let thisT = this;    console.log("1,老铁没毛病" + thisT.data.isLead);    if (!thisT.data.new_userImage) {      wx.showModal({        content: '没有图片可保存~',        showCancel: false,        confirmText: '明白了',      })      return    } else {      if (!thisT.data.isLead) {        wx.showModal({          content: '即将展示广告,看完广告即可下载',          showCancel: true,          confirmText: '确认',          success(res) {            if (res.confirm) {              console.log("222点击确定,老铁没毛病");              //展示激励性广告              if (!instanceRewardedAds.isEnded) {                console.log("333点击确定,老铁没毛病");                instanceRewardedAds.showAd();                thisT.data.isLead = true;                console.log("2,老铁没毛病" + thisT.data.isLead);                return;              }            }          }        })      } else {        wx.showLoading({          title: '保存中...'        })        let that = this        wx.saveImageToPhotosAlbum({          filePath: that.data.new_userImage,          success(res) {            wx.hideLoading();            wx.showModal({              content: '图片已保存到相册了~',              showCancel: false,              confirmText: '保存成功',              success(res) {                if (res.confirm) {                  console.log("点击确定,老铁没毛病");                 // instanceRewardedAds.resetAd(); //下次还需要继续看广告                  // thisT.data.isLead=false;                }              }            })          },          fail() {            wx.hideLoading();            instanceRewardedAds.resetAd(); //下次还需要继续看广告            thisT.data.isLead=false;          }        })      }    }  },  bigimg: function (e) {    if (this.data.userImage) {      this.setData({        photo_select_idx: e.currentTarget.dataset.item      });      this.drawImg(this.data.userImage, this.data.photo_select_idx);    }  },  //绘图  drawImg(headImg, index) {    let that = this    wx.showLoading({      title: '头像生成中...',    })
    let promiseHead = new Promise((resolve, reject) => {      wx.getImageInfo({        src: headImg,        success(res) {          resolve(res)        },        fail(e) {          reject("调用失败head");          wx.hideLoading()        }      })    })    Promise.all([promiseHead]).then(promiseRes => {      let num = 1024      let width_userIcon = num      let x_userIcon = (num - (num)) / 2      let frameImgUrl = that.data.photo_bj_num[index];      const query = wx.createSelectorQuery()      query.select('#genimg')        .fields({          node: true,          size: true        })        .exec((res) => {          const canvas = res[0].node          const ctx = canvas.getContext('2d');          // 初始化画布大小          const dpr = wx.getWindowInfo().pixelRatio;          canvas.width = 1024 * dpr          canvas.height = 1024 * dpr          ctx.scale(dpr, dpr)          const bg1 = canvas.createImage();          const bg2 = canvas.createImage();          bg1.src = promiseRes[0].path;          bg1.onload = () => {            ctx.drawImage(bg1, x_userIcon, x_userIcon, width_userIcon, width_userIcon);            bg2.onload = () => {              ctx.drawImage(bg2, 0, 0, num, num);            }            bg2.src = frameImgUrl;          }          setTimeout(() => {            // 第一个参数为false,表示先清空画布再绘制            wx.canvasToTempFilePath({              x: 0,              y: 0,              width: num,              height: num,              destWidth: num,              destHeight: num,              canvas,              quality: 1,              success(res) {                that.setData({                  new_userImage: res.tempFilePath,                  new_showuserImage: true,                  userImage: headImg                })                wx.hideLoading()              },              fail(res) {                console.log("绘图错误:" + JSON.stringify(res));                wx.hideLoading();              }            }, that);          }, 1000);        })    }).catch(e => console.log(e));  }})

index.json文件

{  "navigationBarTitleText": "点击更多制作证件照",  "usingComponents": {}}

国庆头像制作小程序相关代码大致如上,如有需要可以自行自作。小编是自己加了鉴黄设置哦。提前祝大家国庆快乐呀。预览:

标签:function,console,res,代码,头像,国庆,data,imageUrl,wx
From: https://blog.csdn.net/wxm994116/article/details/142615762

相关文章