你的位置:首页 > 操作系统

[操作系统]简单的为图片添加水印


 1 package com.zzw.addwatermark; 2  3 import android.app.Activity; 4 import android.graphics.Bitmap; 5 import android.graphics.Canvas; 6 import android.graphics.Bitmap.Config; 7 import android.graphics.Color; 8 import android.graphics.Paint; 9 import android.graphics.drawable.BitmapDrawable;10 import android.graphics.drawable.Drawable;11 import android.os.Bundle;12 import android.view.Menu;13 import android.view.MenuItem;14 import android.widget.ImageView;15 16 17 public class MainActivity extends Activity {18 19   @Override20   protected void onCreate(Bundle savedInstanceState) {21     super.onCreate(savedInstanceState);22     setContentView(R.layout.activity_main);23     24     ImageView imageView=(ImageView) findViewById(R.id.imageView);25     26     //使用drawable里面的一张图片,我的头像为例27     Drawable drawable=getResources().getDrawable(R.drawable.test);28     29     //把Drawable转换为Bitmap30     BitmapDrawable bd=(BitmapDrawable) drawable; 31     Bitmap bm=bd.getBitmap();32     33     //为Bitmap添加水印34     Bitmap bitmap=createWatermark(bm, "www.cnblogs.com/zzw1994");35     imageView.setImageBitmap(bitmap);36   }37   38   // 为图片target添加水印文字 39   // Bitmap target:被添加水印的图片 40   // String mark:水印文章 41   private Bitmap createWatermark(Bitmap target,String mark){42     int width=target.getWidth();43     int height=target.getHeight();44     45     Bitmap bitmap=Bitmap.createBitmap(width, height, Config.ARGB_8888);46     Canvas canvas=new Canvas(bitmap);47     48     Paint paint=new Paint();49     50     //设置水印的颜色51     paint.setColor(Color.RED);52     //设置水印字体的大小53     paint.setTextSize(10);54     55     //去锯齿56     paint.setAntiAlias(true);57     //获取原图片的内容58     canvas.drawBitmap(target, 0, 0, paint);59     // 在最下方的左边位置开始添加水印 60     canvas.drawText(mark, 0, height, paint);61     62     canvas.save(Canvas.ALL_SAVE_FLAG);63     canvas.restore();64     65     66     return bitmap;67   }68   69 }