Android圖片添加文字保存到指定文件夾

jopen 12年前發布 | 62K 次閱讀 Android Android開發 移動開發

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(); }

    }

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!