Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 為圖片打上水印

android 為圖片打上水印

編輯:關於Android編程

說起水印其實很簡單,就是在一張圖片上面畫上另一張圖片或文字

實現如下:

package com.tang.watermark;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	ImageView imageView;
	Bitmap mark;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView1); 
		imageView.setImageResource(R.drawable.heihei);
		mark = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
		
		
		Button button = (Button) findViewById(R.id.button1);
		
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bitmap temp = watermark(drawableToBitmap(imageView.getDrawable()),mark,50,100);
				imageView.setImageBitmap(temp);
			}
		});
	}
    /**
     * 將bitmap轉換為Drawable
     * @param bitmap
     * @return
     */
    public static Drawable bitmapToDrawable(Bitmap bitmap)
    {
    	BitmapDrawable bd = new BitmapDrawable(bitmap);
    	return bd;
    }
    
    /**
     * @param src
     * @param bg
     * @param color
     * @return
     */
    public static Bitmap watermark(Bitmap src,Bitmap mark,int x,int y)
	{
		int w = src.getWidth();  
	    int h = src.getHeight();  
	    Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
	    Canvas cv = new Canvas(newb);   
	    cv.drawBitmap(src, 0, 0, null ); 
	    cv.drawBitmap(mark,x, y, null );
	    cv.save( Canvas.ALL_SAVE_FLAG );//保存  
	    cv.restore();//存儲  
	    return newb;
	}
    
	
    /**
     * Drawable 轉換為Bitmap
     * @param drawable
     * @return
     */
	public static Bitmap drawableToBitmap(Drawable drawable) {  
        // 取 drawable 的長寬  
        int w = drawable.getIntrinsicWidth();  
        int h = drawable.getIntrinsicHeight();   
        // 取 drawable 的顏色格式  
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
                : Bitmap.Config.RGB_565;  
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);   
        Canvas canvas = new Canvas(bitmap);  
        drawable.setBounds(0, 0, w, h);  
        drawable.draw(canvas);  
        return bitmap;  
    }  

}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved