美文网首页
android app分享微信小程序(包含封面网络图片)+图片到

android app分享微信小程序(包含封面网络图片)+图片到

作者: hao_developer | 来源:发表于2020-11-09 09:48 被阅读0次

    A 分享微信小程序效果:

    image.png

    实现代码

    //第一步通过url拿网络图片并生成bitmap       
    val path = "分享小程序某个界面包含传参数"
    if (!TextUtils.isEmpty(imgPath)){
        object : AsyncTask<Void, Void, Bitmap>(){
           override fun doInBackground(vararg params: Void?): Bitmap {
              return ImageLoadUtils.getBitmap(context,imgPath)
           }
          override fun onPostExecute(result: Bitmap?) {
               super.onPostExecute(result)
                  result?.let {
                       PublicTools.tools.shareToWxProudct(context,path,it)
                  }
              }
       }.execute()
      }else{
         val bitmap = BitmapFactory.decodeResource(context.resources,R.mipmap.ic_image_6)
         PublicTools.tools.shareToWxProudct(context,path,bitmap)
    }
    

    分享商品到小程序

    //分享商品到小程序
        fun shareToWxProudct(context: Context,path:String,bitmap: Bitmap){
            val name = SPUtils.spUtils.get(context,MyParms.NICK_NAME,"") as String
            val api = WXAPIFactory.createWXAPI(context, MyParms.APPID)
            val miniProgramObj = WXMiniProgramObject()
            miniProgramObj.webpageUrl = " "
            if (BuildConfig.isDebug){
                miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW
            }else{
                miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE
            }
            if (BuildConfig.isDebug){
                miniProgramObj.userName = MyParms.WX_APPGH_DUG // 小程序原始id
            }else{
                miniProgramObj.userName = MyParms.WX_APPGH // 小程序原始id
            }
            miniProgramObj.path = path
            val msg = WXMediaMessage(miniProgramObj)
            msg.title = "${name}邀请您加入小程序" // 小程序消息title
            msg.description = "邀请您加入小程序" // 小程序消息desc
            //bitmap.height*5/4 ,bitmap.height
            val newBitmap = ImageLoadUtils.drawWXMiniBitmap(bitmap,bitmap.width ,bitmap.height)
            if (ImageLoadUtils.isOverSize(newBitmap,128)){//判断bitmap size是否大于128  大于在进行压缩
                val ysBitmap = ImageLoadUtils.zoomImage(newBitmap,300.0,240.0)
                msg.thumbData = ImageLoadUtils.createBitmapThumbnail(ysBitmap,128)   // 小程序消息封面图片,小于128k
            }else{
                msg.thumbData = ImageLoadUtils.createBitmapThumbnail(newBitmap,128)  // 小程序消息封面图片,小于128k
            }
            bitmap.recycle()
            val req = SendMessageToWX.Req()
            req.transaction = "惊喜汇"//buildTransaction("miniProgram")
            req.message = msg
            req.scene = SendMessageToWX.Req.WXSceneSession // 目前只支持会话
            api.sendReq(req)
        }
    

    设置生成bitmap大小

    //设置生成bitmap大小
    public static Bitmap drawWXMiniBitmap(Bitmap bitmap, int width, int height) {
            Bitmap mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            // 用这个Bitmap生成一个Canvas,然后canvas就会把内容绘制到上面这个bitmap中
            Canvas mCanvas = new Canvas(mBitmap);
            // 绘制画笔
            Paint mPicturePaint = new Paint();
            // 绘制背景图片
            mCanvas.drawBitmap(mBitmap, 0.0f, 0.0f, mPicturePaint);
            // 绘制图片的宽、高
            int width_head = bitmap.getWidth();
            int height_head = bitmap.getHeight();
            // 绘制图片--保证其在水平方向居中
            mCanvas.drawBitmap(bitmap, (width - width_head) / 2, (height - height_head) / 2,
                    mPicturePaint);
            // 保存绘图为本地图片
            mCanvas.save();
            mCanvas.restore();
            return mBitmap;
        }
    

    微信分享bitmap不能大于128k

    /**
         * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
         *
         * @param bitmap
         * @param maxKb
         * @return
         */
        public static byte[] createBitmapThumbnail(Bitmap bitmap, int maxKb) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            int options = 100;
            while (output.toByteArray().length > maxKb && options != 10) {
                output.reset();
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, output);
                options -= 10;
            }
            return output.toByteArray();
        }
    

    判断bitmap是否大于128k

    public static boolean isOverSize(Bitmap bitmap, int maxSize) {
         // 将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
         byte[] b = baos.toByteArray();
         // 将字节换成KB
        double mid = b.length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        return mid > maxSize;
    }
    

    压缩bitmap指定宽高

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                       double newHeight) {
       // 获取这个图片的宽和高
      float width = bgimage.getWidth();
      float height = bgimage.getHeight();
      // 创建操作图片用的matrix对象
      Matrix matrix = new Matrix();
       // 计算宽高缩放率
      float scaleWidth = ((float) newWidth) / width;
      float scaleHeight = ((float) newHeight) / height;
      // 缩放图片动作
      matrix.postScale(scaleWidth, scaleHeight);
      Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
      (int) height, matrix, true);
      return bitmap;
    }
    



    B 分享当前view到朋友圈

    val bmp = PublicTools.tools.createBitmapFromView(llPostLay)
    bmp?.let {
        val api = WXAPIFactory.createWXAPI(context, MyParms.APPID)
        val imgObj = WXImageObject(it)
    
        val msg = WXMediaMessage()
        msg.mediaObject = imgObj
        msg.thumbData = PublicTools.tools.bmpToByteArray(it,32)
    
        val req = SendMessageToWX.Req()
        req.transaction = PublicTools.tools.buildTransaction("img")
       req.message = msg
       req.scene = SendMessageToWX.Req.WXSceneTimeline
       api.sendReq(req)
    

    把view生成bitmap

    /**
         * 该方式原理主要是:View组件显示的内容可以通过cache机制保存为bitmap
         */
        fun createBitmapFromView(view: View): Bitmap? {
            var bitmap: Bitmap? = null
            //开启view缓存bitmap
            view.isDrawingCacheEnabled = true
            //设置view缓存Bitmap质量
            view.drawingCacheQuality = DRAWING_CACHE_QUALITY_HIGH
            //获取缓存的bitmap
            val cache = view.drawingCache
            if (cache != null && !cache.isRecycled) {
                bitmap = Bitmap.createBitmap(cache)
            }
            //销毁view缓存bitmap
            view.destroyDrawingCache()
            //关闭view缓存bitmap
            view.isDrawingCacheEnabled = false
            return bitmap
        }
    

    相关文章

      网友评论

          本文标题:android app分享微信小程序(包含封面网络图片)+图片到

          本文链接:https://www.haomeiwen.com/subject/vzjfbktx.html