image.png
/**
* 该方式原理主要是:View组件显示的内容可以通过cache机制保存为bitmap
*/
fun createBitmapFromView(view: View): Bitmap {
val bitmap = Bitmap.createBitmap(view.width, view.height,Bitmap.Config.RGB_565)
val canvas = Canvas(bitmap)
view.draw(canvas)
return bitmap
}
bitmap转byteArray
fun wxBmpToByteArray(bmp: Bitmap,needRecycle: Boolean): ByteArray? {
val output = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
if (needRecycle) {
bmp.recycle()
}
val result = output.toByteArray()
try {
output.close()
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return result
}
调用案例
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
val thumbBmp = Bitmap.createScaledBitmap( it,150,150, true )
msg.thumbData = PublicTools.tools.wxBmpToByteArray(thumbBmp,true)
it.recycle()
val req = SendMessageToWX.Req()
req.transaction = PublicTools.tools.buildTransaction("img")
req.message = msg
req.scene = SendMessageToWX.Req.WXSceneTimeline
api.sendReq(req)
}
网友评论