1. 程式人生 > >Android bitmap合成圖片

Android bitmap合成圖片

//根據專案需要,在一張圖片上合成另一張圖片(壓縮後的),顯示到預覽圖的imageview上,然後分享出去

大致思路:1,獲取網路圖片,計算寬高

  2,預定於壓縮後圖片的寬高(也可是相對螢幕寬高的百分比,方便適配)

  3,進行縮放bitmapB

  4,建立合成後的圖片bitmapC

  5,建立底部本地圖片的bitmapA

  6,把bitmapA和bitmapB用畫筆畫到bitmapC上

  7,然後用message通知handler顯示到預覽圖上

,,,,,,,,下面是具體實現程式碼,,,,,,,,,,,,,,,,,,,,,,

在onCreate方便實現

new Thread(new 
Runnable() { @Override public void run() { //建立一個message //設定what欄位的值為UPDATE_TEXT,主要是為了區分不同的message //設定message.obj的內容 //呼叫Handler的message物件 //handler中的handlermessage物件是在主執行緒中執行的 Message message = new Message(); message.what = UPDATE_TEXT; message.obj = compositeImages();
handler.sendMessage(message); } }).start();

下面是handler更新UI

private Handler handler = new Handler() {

    public void handleMessage(Message msg) {
        switch (msg.what) {
            case UPDATE_TEXT:
                //在這裡可以進行UI操作
                //對msg.obj進行String強制轉換
Bitmap a = (Bitmap) msg.obj
; // 微信分享 bitmap=a; share_iv.setImageBitmap(a); break; } } };

然後是分享,

@OnClick({ R.id.toolbar_back,R.id.toolbar_share})
public void onClick(View view) {
    switch (view.getId()){
        case R.id.toolbar_back:
            this.finish();
            break;
        case R.id.toolbar_share:
            shareAction.open();
            break;
}
}

private ShareAction shareAction = new ShareAction(ShareActivity.this)
        .setDisplayList(SHARE_MEDIA.WEIXIN,SHARE_MEDIA.WEIXIN_CIRCLE)
        .setShareboardclickCallback(new ShareBoardlistener() {
            @Override
public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                UMImage image = new UMImage(ShareActivity.this, bitmap);//本地檔案
String uid=LocalStorage.get("user_id").toString();
                int l=uid.length();

                String string="我是的第"+uid+"個使用者";
                switch (share_media) {
                    case WEIXIN:
                        new ShareAction(ShareActivity.this).setPlatform(share_media).setCallback(shareListener)
                                .withText(string)
                                .withMedia(image)
                                .setCallback(shareListener)
                                .share();
                        break;
                    case WEIXIN_CIRCLE:
                        new ShareAction(ShareActivity.this).setPlatform(share_media).setCallback(shareListener)
                                .withText(string)
                                .withMedia(image)
                                .setCallback(shareListener)
                                .share();
                        break;
}
            }
        });
private UMShareListener shareListener = new UMShareListener() {
    /**
     * @descrption 分享開始的回撥
     * @param platform 平臺型別
     */
@Override
public void onStart(SHARE_MEDIA platform) {

    }

    /**
     * @descrption 分享成功的回撥
     * @param platform 平臺型別
     */
@Override
public void onResult(SHARE_MEDIA platform) {
        MobclickAgent.onEvent(getApplicationContext(), "share");
//獲取是否是今天抽獎
String upLoad_day=mStoreUtils.getUserUploadLuckDate();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String nowDay = sf.format(now);
mStoreUtils.setUserShareDate(nowDay);
        if (nowDay.equals(upLoad_day)){
           int share_time= mStoreUtils.getUnreadMsgShare();
            if (share_time<2){
                int luck_time=mStoreUtils.getSumLuck();
mStoreUtils.setSumLuck(luck_time-2);
mStoreUtils.setSumLuckShare(share_time+1);
}else {

            }

        }else {
            mStoreUtils.setSumLuckShare(0);
            int luck_time=mStoreUtils.getSumLuck();
mStoreUtils.setSumLuck(luck_time-2);
mStoreUtils.setUserUploadLuckDate(nowDay);
}

    }

    /**
     * @descrption 分享失敗的回撥
     * @param platform 平臺型別
     * @param t 錯誤原因
     */
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
    }

    /**
     * @descrption 分享取消的回撥
     * @param platform 平臺型別
     */
@Override
public void onCancel(SHARE_MEDIA platform) {

    }
};

最後是被問的重點-合成圖片

 private Bitmap compositeImages(){
        String ph= LocalStorage.get("avatar").toString();
System.out.println("ph:="+ph);
Bitmap dstBitmap=getBitmapFromUri(ph);
//獲取這個圖片的寬和高
int width = dstBitmap.getWidth();
        int height = dstBitmap.getHeight();
//定義預轉換成的圖片的寬度和高度
DisplayMetrics dm = new DisplayMetrics();
//獲取螢幕資訊
getWindowManager().getDefaultDisplay().getMetrics(dm);
         int screenWidth = dm.widthPixels;
        int newWidth = screenWidth/7;
        int newHeight = screenWidth/7;
//計算縮放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
// 建立操作圖片用的matrix物件
Matrix matrix = new Matrix();
// 縮放圖片動作
matrix.postScale(scaleWidth, scaleHeight);
// 建立新的圖片
Bitmap resizedBitmap = Bitmap.createBitmap(dstBitmap, 0, 0,
width, height, matrix, true);
//        Bitmap dstBitmap=BitmapFactory.decodeResource(getResources(), R.mipmap.news_pressed);
Bitmap srcBitmap= BitmapFactory.decodeResource(getResources(), R.mipmap.start_page1_share);
Bitmap bmp = null;
//下面這個Bitmap中建立的函式就可以建立一個空的Bitmap
System.out.println("srcBitmap.getWidth():="+srcBitmap);
bmp = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());
Paint paint = new Paint();
Canvas canvas = new Canvas(bmp);
//首先繪製第一張圖片,很簡單,就是和方法中getDstImage一樣
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
canvas.drawBitmap(resizedBitmap, 20, 10, paint);
paint.setTextSize(getResources().getDimensionPixelSize(R.dimen.set_text_size));
String uid=LocalStorage.get("user_id").toString();
        int l=uid.length();
        if (l<7)
        {
            if (l==3){
                uid="1111"+uid;
}else if(l==4){
                uid="111"+uid;
}else if(l==5){
                uid="11"+uid;
}else if(l==6){
                uid="1"+uid;
}

        }
        String string="我是第"+uid+"個使用者";
canvas.drawText( string,srcBitmap.getWidth()/3, screenWidth/13,paint );
canvas.drawBitmap(srcBitmap, 0, 0, paint);
//在繪製第二張圖片的時候,我們需要指定一個Xfermode
        //這裡採用Multiply模式,這個模式是將兩張圖片的對應的點的畫素相乘
        //,再除以255,然後以新的畫素來重新繪製顯示合成後的影象
return bmp;
}
    private Bitmap getBitmapFromUri(String uri) {
        Bitmap map = null;
        try {
            // 讀取uri所在的圖片
//            Bitmap bitmap = MediaStore.Images.Media.getBitmap(SetActivity.this.getContentResolver(), uri);
URL url = new URL(uri);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
// TODO Auto-generated catch block
return map;
} catch (Exception e) {
            System.out.println("eeeeeeeeeee:="+e);
e.printStackTrace();
            return null;
}
    }