收藏
回答

微信 分享链接 和 网络图片 网络图片出不来?

WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = url;
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title = title;
msg.description = content;

Resources res = context.getResources();
Bitmap bmp = null;

if (imageUrl.isEmpty()){
   bmp= BitmapFactory.decodeResource(res, R.mipmap.appicon);
   Bitmap thumbBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
   msg.thumbData = WxUtil.bmpToByteArray(thumbBitmap,true);
}else {
   new Thread(){
      @Override
      public void run() {
         super.run();
         // 涉及到下载图片,调用netToLoacalBitmap时要放在子线程中
         Bitmap bitmap = netToLoacalBitmap(imageUrl);
         int WX_THUMB_SIZE = 120;

        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, WX_THUMB_SIZE, WX_THUMB_SIZE, true);
        msg.thumbData = WxUtil.bmpToByteArray(thumbBitmap,true);
      }
   }.start();
}
SendMessageToWX.Req req = new SendMessageToWX.Req();    //创建一个请求对象
req.message = msg;  //把msg放入请求对象中
req.scene = type;    //设置发送到朋友圈
//req.scene = SendMessageToWX.Req.WXSceneSession;   //设置发送给朋友
req.transaction = tag;  //这个tag要唯一,用于在回调中分辨是哪个分享请求
if(CommonAppContext.api==null){
   CommonAppContext.api = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
   CommonAppContext.api.registerApp(Constants.WX_APP_ID);
}

/**
 * todo 将网络资源图片转换为Bitmap
 * @param imgUrl 网络资源图片路径
 * @return Bitmap
 * 该方法调用时要放在子线程中
 */
public static Bitmap netToLoacalBitmap(String imgUrl){
   Bitmap bitmap = null;
   InputStream in=null;
   BufferedOutputStream out = null;
   try{
      in = new BufferedInputStream(new URL(imgUrl).openStream(),1024);
      final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
      out = new BufferedOutputStream(dataStream,1024);
      copy(in,out);
      out.flush();
      byte[] data = dataStream.toByteArray();
   // bitmap = BitmapFactory.decodeByteArray(data,0,data.length);


      YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 150,150, null);//20、20分别是图的宽度与高度
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      yuvimage.compressToJpeg(new Rect(0, 0,20, 20), 80, baos);//80--JPG图片的质量[0-100],100最高
      byte[] jdata = baos.toByteArray();

      bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
      Log.e("--------bitmap--",bitmap+"");

      data = null;
      return bitmap;
   }catch (IOException e){
      e.printStackTrace();
      return null;
   }
}
回答关注问题邀请回答
收藏

1 个回答

  • Demons
    Demons
    2022-06-30

    提供一下复现链接

    2022-06-30
    有用
    回复
登录 后发表内容