美文网首页
android 分享bitmap到微信

android 分享bitmap到微信

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

    微信分享文档【https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/Android.html

    引用:

    implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
    

    分享代码:

    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
            //微信朋友:SendMessageToWX.Req.WXSceneSession
            //微信圈:SendMessageToWX.Req.WXSceneTimeline
            req.scene = SendMessageToWX.Req.WXSceneTimeline
            api.sendReq(req)
      }
    

    msg.thumbData = PublicTools.tools.bmpToByteArray(it,32)需要注意不能大于32K

    /**
         * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
         * @param bitmap
         * @param maxkb
         * @return
         */
        fun bmpToByteArray(bitmap: Bitmap, maxkb: Int): ByteArray? {
            val output = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
            var options = 100
            while (output.toByteArray().size > maxkb && options != 10) {
                output.reset() //清空output
                bitmap.compress(
                    Bitmap.CompressFormat.JPEG,
                    options,
                    output
                ) //这里压缩options%,把压缩后的数据存放到output中
                options -= 10
            }
            bitmap.recycle()
            return output.toByteArray()
        }
    

    相关文章

      网友评论

          本文标题:android 分享bitmap到微信

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