安卓開發之如何在微信分享中載入網狀圖片作為縮圖

來源:互聯網
上載者:User

這幾天在做的一個項目是有一個分享到微信的功能,要實現在分享中添加標題、描述、連結、縮圖實現分享。先來看一下官方的API文檔:

網頁類型分享樣本:

//初始化一個WXWebpageObject對象,填寫url
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = "網頁url";
//用WXWebpageObject對象初始化一個WXMediaMessage對象,填寫標題、描述
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title = "網頁標題";
msg.description = "網頁描述";
Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);
msg.thumbData = Util.bmpToByteArray(thumb, true);
 //構造一個Req
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");//transaction欄位用於唯一標識一個請求
req.message = msg;
req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
//調用api介面發送資料到微信
api.sendReq(req);

縮圖的設定,就是這一行代碼:

msg.thumbData=某bitmap
可見,官方的API只提供了載入本地資源圖片的樣本,並沒有給出載入網狀圖片作為縮圖的範例程式碼,當然也很容易實現,只要我們把網狀圖片轉換為Bitmap對象就可以了,可是,當我使用自訂的Bitmap時候,卻總是報錯,並且報錯也不給出任何提示資訊,最後才知道微信分享縮圖(thumb)最大64KB,居然有這麼一個限制,所以只好做一些處理了。所有實現代碼如下:

網狀圖片轉換為Bitmap對象代碼:

/**
 * 把網路資源圖片轉化成bitmap
 * @param url  網路資源圖片
 * @return  Bitmap
 */
public static Bitmap GetLocalOrNetBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    try {
        in = new BufferedInputStream(new URL(url).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);
        data = null;
        return bitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

private static void copy(InputStream in, OutputStream out)
        throws IOException {
    byte[] b = new byte[1024];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}

然後把範例程式碼裡的那兩行改為如下即可:

Bitmap thumb =Bitmap.createScaledBitmap(GetLocalOrNetBitmap("某網路資源圖片"), 120, 120, true);//壓縮Bitmap
msg.thumbData = Util.bmpToByteArray(thumb, true);

問題解決,成功實現微信分享。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.