微信原生分享(32kb限制)

关于微信分享,我之前用到的微信分享,都是使用的三方分享SDK,毕竟人家处理后的东西会方便很多,如Mob和友盟的。

现在因为公司的要求要单独集成微信分享

具体步骤如下:

1、申请应用,获取appid

2、添加依赖并配置

3、创建WXEntryActivity(必须)

4、创建工具类并开始使用

这些步骤在此不做详细说明,如有需要可以看如下两篇文章

微信官方:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317340&token=&lang=zh_CN

集成步骤可以看下此篇文章:https://blog.csdn.net/baidu_35559769/article/details/82497289

此篇文章主要完善一下压缩类,和一些观点的指正

声明:网上好多文章都说链接分享的图不能大于32kb,请问都自己试过吗

不知道是微信改了还是怎么滴,我不断测试后,得出如下几轮

经测试最大是400,400,我这里设成300,300,而质量压缩并没有觉得有用,知识网上说了,最大32kb,所以我就写了32,其实写70也一样

为了保证分享没有问题,特此在进行尺寸压缩后,进行了质量压缩,保证不超过32kb,现将分享工具类和压缩工具类代码粘上

/*
* 微信分享工具类
* */
public class WxShareUtils {
    /*
    * 链接分享,网络链接获取图片bitmap并分享到为微信
    * */


    public static void setHttpImgUrlShare(final Context mContext, final String webUrl, final String title, final String desc, String thumbImage, final String toType){

        Glide.with(mContext).load(thumbImage).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                //经测试最大是400,400,我这里设成300,300,而质量压缩并没有觉得有用,知识网上说了,最大32kb,所以我就写了32,其实写70也一样
                Bitmap bitmap = ImageUtil.WxscaleImg(resource,300,300);
                Bitmap thumbBmp = FileUtils.inputPicCompress(bitmap, 32);
                shareWeb(mContext,webUrl,title,desc,thumbBmp,toType);
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                shareWeb(mContext,webUrl,title,desc,null,toType);
            }
        });

    }

    /*
    * 图片分享
    * */
    public static void setImgUrlShare(final Context mContext, final String imgUrl,final String desc, final String toType){
        if(!StringUtilInput.isEmpty(desc)) {
            ClipboardManager clipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setText(desc);
            ToastUtil.createToastConfig().showIJXToast(mContext, "已复制文字内容", 1);
        }
        Glide.with(mContext).load(imgUrl).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                shareImg(mContext,resource,toType);
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                ToastUtil.createToastConfig().showToast(mContext,"图片获取失败啦");
            }
        });

    }


    /**
     * 分享网页类型至微信
     *
     * @param mContext 上下文
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param desc 网页描述
     * @param bitmap  位图
     * @param toType  分享到什么平台
     */
    private static void shareWeb(Context mContext, String webUrl, String title, String desc, Bitmap bitmap,String toType) {
        // 通过appId得到IWXAPI这个对象
        IWXAPI wxapi = WXAPIFactory.createWXAPI(mContext, wxAppId);
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled()) {
            ToastUtil.createToastConfig().showToast(mContext,"您还没有安装微信");
            return;
        }

        // 初始化一个WXWebpageObject对象
        WXWebpageObject webpageObject = new WXWebpageObject();
        // 填写网页的url
        webpageObject.webpageUrl = webUrl;

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        // 填写网页标题、描述、位图
        msg.title = title;
        msg.description = desc;
        // 如果没有位图,可以传null,会显示默认的图片
        msg.setThumbImage(bitmap);

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求(可自定义)
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈

        if(!StringUtilInput.isEmpty(toType)&&toType.equals("wxq")){
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }else {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        // 向微信发送请求
        wxapi.sendReq(req);
    }

/*
* 分享图片
* */
    private static void shareImg(Context mContext, Bitmap bitmap,String toType) {
        // 通过appId得到IWXAPI这个对象
        IWXAPI wxapi = WXAPIFactory.createWXAPI(mContext, wxAppId);
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled()) {
            ToastUtil.createToastConfig().showToast(mContext,"您还没有安装微信");
            return;
        }

        Bitmap bp = bitmap;
        WXImageObject wxImageObject = new WXImageObject(bp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //设置缩略图
        String aaa = bitmap.getHeight()+"***"+bitmap.getWidth();
        Bitmap mBp = Bitmap.createScaledBitmap(bp, 120, 120, true);
        bp.recycle();
        msg.thumbData = bmpToByteArray(mBp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//  transaction字段用
        req.message = msg;
//        req.scene = SendMessageToWX.Req.WXSceneSession;
        if(!StringUtilInput.isEmpty(toType)&&toType.equals("wxq")){
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }else {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        wxapi.sendReq(req);
    }




    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


}
StringUtilInput.isEmpty()是非空判断,在此不贴工具类了

里边的代码一般均有注释

以下为图片压缩工具类

/**
 * 作者:liukai
 * 创建时间:2018/1/4 13:31
 * 邮箱:liukai3099@163.com
 */
public class ImageUtil {
 
    /**
     * 描述:比例压缩,同上,修改适用于微信分享
     *
     * @param bitmap the bitmap
     * @param maxWidth 图片最大的宽
     * @param maxHeight 图片最大的高
     * @return Bitmap 新图片
     */
    public static Bitmap WxscaleImg(Bitmap bitmap, int maxWidth, int maxHeight) {
        if(bitmap == null){
            return null;
        }
        if(maxHeight<=0 || maxWidth<=0){
            return bitmap;
        }

        try {

            // 获得图片的宽高
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();

            if(width <= 0 || height <= 0){
                return null;
            }
            // 计算缩放比例
            float scaleWidth = ((float) maxWidth) / width;
            float scaleHeight = ((float) maxHeight) / height;
            if(scaleWidth>1){
                scaleWidth = 1;
            }
            if(scaleHeight>1){
                scaleHeight = 1;
            }
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            //得到新的图片
            Bitmap newBm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,true);
            return newBm;
        }catch (Exception e){
            return bitmap;
        }

    }

       
}
/**
 * Created by lk
 */
public class FileUtils {

    /*
     * 图片压缩,不保存到sd卡
     * */
    public static  Bitmap inputPicCompress(Bitmap bitmap, int num) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
            int options = 99;
            String aaa = baos.toByteArray().length+"";
            while (baos.toByteArray().length / 1024 > num) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                String bbb = baos.toByteArray().length+"";
                baos.reset();//重置baos即清空baos
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
                if (options >= 10) {
                    options -= 2;//每次都减少2
                } else {
                    break;
                }
            }
            String ccc = baos.toByteArray().length+"";
            // 把压缩后的数据baos存放到ByteArrayInputStream中
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
            // 把ByteArrayInputStream数据生成图片
//            Bitmap bitmapNew = BitmapFactory.decodeStream(isBm, null, null);
            byte[] bytes = baos.toByteArray();
            Bitmap bitmapNew = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmapNew;
        }catch (Exception e){
            return bitmap;
        }

    }
   
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值