我们在发微博或者csdn博文的时候都可以给图片加上一个水印,一个独立的标识,那是怎么实现的呢?先封装一个BitmapTools封装类,该类要解决的问题是一将突破存储至sdcard中,二给图片加上水印。
BitmapTools
package com.example.g11_bitmap04;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Paint;import android.os.Environment;public class BitmapTools { public BitmapTools() { // TODO Auto-generated constructor stub } public static Bitmap createBitmap(Resources resources, int resid, String name) { Bitmap bitmap=BitmapFactory.decodeResource(resources, resid); //复制一份新的Bitmap,因为不能直接在原有的bitmap上进行水印操作 //Bitmap.config存储的格式 Bitmap newBitmap=bitmap.copy(Bitmap.Config.ARGB_8888, true); //使用自定义画布 Canvas canvas=new Canvas(newBitmap); Paint paint=new Paint(); paint.setTextSize(200); canvas.drawText("hello", 100, 100, paint); //判断SDcard是否在可用状态 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //直接将图片保存在根目录下 File root=Environment.getExternalStorageDirectory(); OutputStream outputStream=null; try { outputStream=new FileOutputStream(new File(root, name)); //对图片进行压缩并以png格式,保存在sdcard中 newBitmap.compress(Bitmap.CompressFormat.PNG, 50, outputStream); } catch (Exception e) { // TODO: handle exception } } return newBitmap; }}
MainActivtiy中调用该方法
package com.example.g11_bitmap04;import android.os.Bundle;import android.app.Activity;import android.graphics.Bitmap;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity { private ImageView imageView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView=(ImageView)this.findViewById(R.id.imageView1); button=(Button)this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Bitmap bitmap=BitmapTools.createBitmap(getResources(), R.drawable.a, "a.png"); imageView.setImageBitmap(bitmap); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}