Android图片添加文字保存到指定文件夹

jopen 11年前

package com.example.imagetest;    import java.io.File;  import java.io.FileNotFoundException;  import java.io.FileOutputStream;  import java.io.IOException;  import android.os.Bundle;  import android.app.Activity;  import android.content.Context;  import android.graphics.Bitmap;  import android.graphics.BitmapFactory;  import android.graphics.Canvas;  import android.graphics.Color;  import android.graphics.Paint;  import android.graphics.Rect;  import android.graphics.Typeface;  import android.widget.ImageView;    /**   * 图片上写字demo   *   *    * @QQ 7617812 2013-4-23 version 1.0   */  public class MainActivity extends Activity {     @Override   protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);      String str = "要写的文字";      ImageView imageView = (ImageView) this.findViewById(R.id.imageView1);    drawNewBitmap(imageView, str);     }     /**    * 在图片上面写字    *    * @param imageView    * @param str    */   private void drawNewBitmap(ImageView imageView, String str) {    Bitmap photo = BitmapFactory.decodeResource(this.getResources(),      R.drawable.ic_launcher);      int width = photo.getWidth();    int hight = photo.getHeight();    System.out.println("宽" + width + "高" + hight);    Bitmap icon = Bitmap      .createBitmap(width, hight, Bitmap.Config.ARGB_8888); // 建立一个空的BItMap    Canvas canvas = new Canvas(icon);// 初始化画布绘制的图像到icon上      Paint photoPaint = new Paint(); // 建立画笔    photoPaint.setDither(true); // 获取跟清晰的图像采样    photoPaint.setFilterBitmap(true);// 过滤一些      Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标    Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标    canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到                // dst使用的填充区photoPaint      Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG      | Paint.DEV_KERN_TEXT_FLAG);// 设置画笔    textPaint.setTextSize(20.0f);// 字体大小    textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度    textPaint.setColor(Color.RED);// 采用的颜色    canvas.drawText(str, 20, 26, textPaint);// 绘制上去字,开始未知x,y采用那只笔绘制    canvas.save(Canvas.ALL_SAVE_FLAG);    canvas.restore();    imageView.setImageBitmap(icon);    saveMyBitmap(icon,"test");   }     /**    * 保存文件到指定的路径下面    * @param bitmap     * @param bitName  文件名字    */   public void saveMyBitmap(Bitmap bitmap, String bitName) {    File f = new File("/sdcard/ebs/" + bitName + ".png");      FileOutputStream fOut = null;    try {     f.createNewFile();     fOut = new FileOutputStream(f);     bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);     fOut.flush();     fOut.close();    } catch (FileNotFoundException e) {     e.printStackTrace();    } catch (IOException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }     }    }