When posting Weibo or csdn blog posts, we can add a watermark and an independent logo to the image. How can we achieve this? First, encapsulate a BitmapTools encapsulation class. The problem solved by this class is to store the package in sdcard and add watermarks to the image.
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); // copy a new Bitmap because the watermark operation on the original bitmap cannot be performed directly. // Bitmap. the config storage format is Bitmap newBitmap = bitmap. copy (Bitmap. config. ARGB_8888, true); // use custom Canvas canvas Canvas = new Canvas (newBitmap); Paint paint = new Paint (); paint. setTextSize (200); canvas. drawText ("hello", 100,100, paint); // determines whether the SDcard is in the available State if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// Save the image to the root directory File root = Environment. getExternalStorageDirectory (); OutputStream outputStream = null; try {outputStream = new FileOutputStream (new File (root, name); // compress the image in png format, save newBitmap in sdcard. compress (Bitmap. compressFormat. PNG, 50, outputStream);} catch (Exception e) {// TODO: handle exception} return newBitmap ;}}
MainActivtiy calls this method
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;@Overrideprotected 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubBitmap bitmap=BitmapTools.createBitmap(getResources(), R.drawable.a, "a.png");imageView.setImageBitmap(bitmap);}});}@Overridepublic 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;}}