Android 圖片旋轉,縮放,切割

來源:互聯網
上載者:User

最近總結了一下Android中對圖片處理方法,具體如下:

/** * 圖片反轉 * @param img * @return */public Bitmap toturn(Bitmap img){Matrix matrix = new Matrix();matrix.postRotate(90); /*翻轉90度*/int width = bitmap.getWidth();int height =bitmap.getHeight();img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);return img;}/** * 圖片縮放 * @param bigimage * @param newWidth * @param newHeight * @return */public Bitmap tochange(Bitmap bigimage,int newWidth,int newHeight){// 擷取這個圖片的寬和高int width = bigimage.getWidth();int height = bigimage.getHeight();// 建立操作圖片用的matrix對象Matrix matrix = new Matrix();// 計算縮放率,新尺寸除原始大小float scaleWidth = ((float) newWidth)/width;float scaleHeight = ((float) newHeight)/height;// 縮放圖片動作matrix.postScale(scaleWidth, scaleHeight);Bitmap bitmap = Bitmap.createBitmap(bigimage, 0, 0, width, height,matrix, true);return bitmap;}

/**         * 程式切割圖片         * @param bitmap         * @param x         * @param y         * @param w         * @param h         * @return         */        public Bitmap BitmapClipBitmap(Bitmap bitmap,int x, int y, int w, int h) {            return  Bitmap.createBitmap(bitmap, x, y, w, h);        }
/**     * 圖片疊加     * @param b     * @return     */    public Bitmap diejia(Bitmap b){        if(!b.isMutable()){//設定圖片為背景為透明b = b.copy(Bitmap.Config.RGB_565, true);//}Canvas canvas = new Canvas(b);Bitmap lock=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);//疊加新圖b2//注意此時繪製座標是相對於圖片bcanvas.drawBitmap(lock, 0, 0, null);canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();lock.recycle();lock=null;    return b;    }

圖片置中疊加:

Bitmap centerToFit(Bitmap bitmap, int width, int height, Context context) {        final int bitmapWidth = bitmap.getWidth();        final int bitmapHeight = bitmap.getHeight();         if (bitmapWidth < width || bitmapHeight < height) {            int color = context.getResources().getColor(R.color.window_background);             Bitmap centered = Bitmap.createBitmap(bitmapWidth < width ? width : bitmapWidth,                    bitmapHeight < height ? height : bitmapHeight, Bitmap.Config.RGB_565);            centered.setDensity(bitmap.getDensity());            Canvas canvas = new Canvas(centered);            canvas.drawColor(color);            canvas.drawBitmap(bitmap, (width - bitmapWidth) / 2.0f, (height - bitmapHeight) / 2.0f,                    null);             bitmap = centered;        }         return bitmap;    }

/** * 獲得帶倒影的圖片方法 */  public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {     final int reflectionGap = 4;     int width = bitmap.getWidth();     int height = bitmap.getHeight();       Matrix matrix = new Matrix();     matrix.preScale(1, -1);       Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);       Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);       Canvas canvas = new Canvas(bitmapWithReflection);     canvas.drawBitmap(bitmap, 0, 0, null);     Paint deafalutPaint = new Paint();     canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);       canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);       Paint paint = new Paint();     LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);     paint.setShader(shader);     // Set the Transfer mode to be porter duff and destination in     paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));     // Draw a rectangle using the paint with our linear gradient     canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);     return bitmapWithReflection;  }  }  

對映像進行相關參數轉換,重新形成新的圖片資料參數展示形式(Drawble)

 /**     * Create a drawable from file path name.     */public Drawable createFromPath(String pathName) {if (pathName == null) {return null;}BitmapFactory.Options opts = new BitmapFactory.Options();opts.inJustDecodeBounds = true;opts.inJustDecodeBounds = true;BitmapFactory.decodeFile(pathName, opts);opts.inSampleSize = computeSampleSize(opts, -1, 1280 * 720);opts.inJustDecodeBounds = false;Bitmap bm = BitmapFactory.decodeFile(pathName, opts);if (bm != null) {return drawableFromBitmap(null, bm, null, null, pathName);}return null;}private Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,Rect pad, String srcName) {if (np != null) {return new NinePatchDrawable(res, bm, np, pad, srcName);}return new BitmapDrawable(res, bm);}public int computeSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);int roundedSize;if (initialSize <= 8) {roundedSize = 1;while (roundedSize < initialSize) {roundedSize <<= 1;}} else {roundedSize = (initialSize + 7) / 8 * 8;}return roundedSize;}private int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {double w = options.outWidth;double h = options.outHeight;int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));if (upperBound < lowerBound) {// return the larger one when there is no overlapping zone.return lowerBound;}if ((maxNumOfPixels == -1) && (minSideLength == -1)) {return 1;} else if (minSideLength == -1) {return lowerBound;} else {return upperBound;}}

/**      * create the bitmap from a byte array      *產生浮水印圖片      * @param src the bitmap object you want proecss      * @param watermark the water mark above the src      * @return return a bitmap object ,if paramter's length is 0,return null      */      private Bitmap createBitmap( Bitmap src, Bitmap watermark )      {          String tag = "createBitmap";          Log.d( tag, "create a new bitmap" );          if( src == null )          {              return null;          }             int w = src.getWidth();          int h = src.getHeight();          int ww = watermark.getWidth();          int wh = watermark.getHeight();          //create the new blank bitmap          Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//建立一個新的和SRC長度寬度一樣的位元影像          Canvas cv = new Canvas( newb );          //draw src into          cv.drawBitmap( src, 0, 0, null );//在 0,0座標開始畫入src          //draw watermark into          cv.drawBitmap( watermark, w - ww + 5, h - wh + 5, null );//在src的右下角畫入浮水印          //save all clip          cv.save( Canvas.ALL_SAVE_FLAG );//儲存          //store          cv.restore();//儲存          return newb;      }  

private void_Init()   {     m_paint = new Paint(Paint.ANTI_ALIAS_FLAG);     LinearGradient lg = new LinearGradient(       0, 0, 0, m_nShadowH,        0xB0FFFFFF, 0x00000000,       Shader.TileMode.CLAMP);     m_paint.setShader(lg);     m_paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));   }     @Override protected void onDraw(Canvas canvas)   {     super.onDraw(canvas);       int nX = 0;     int nY = 20;       _DrawNormalImg(canvas, nX, nY);     _DrawMirror(canvas, nX, nY);   }      private void  _DrawNormalImg(Canvas canvas, int nX, int nY)   {     canvas.save(Canvas.MATRIX_SAVE_FLAG);     canvas.translate(nX, nY);        m_dw.draw(canvas);     canvas.restore();   }     private void  _DrawMirror(Canvas canvas, int nX, int nY)   {     int nW = m_dw.getIntrinsicWidth();     int nH = m_dw.getIntrinsicHeight();       ///////////////////////////////////     //draw mirror image     canvas.save(Canvas.MATRIX_SAVE_FLAG);     canvas.scale(1.0f, -1.0f);     canvas.translate(nX, -(nY + nH * 2));     canvas.clipRect(0, nH, nW, nH - m_nShadowH);     m_dw.draw(canvas);     canvas.restore();       //////////////////////////////     //draw mask     canvas.save();     canvas.translate(nX, nY + nH);     canvas.drawRect(0, 0, nW, m_nShadowH, m_paint);     canvas.restore();   }  

具有幻象的拖拽效果package com.ql.app;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.Button;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.FrameLayout.LayoutParams;/** * 參考:http://techdroid.kbeanie.com/2010/04/simple-drag-n-drop-on-android.html * @author admin * */public class App extends Activity implements OnTouchListener{private final static int START_DRAGGING = 0;private final static int STOP_DRAGGING = 1;private Button btn;private FrameLayout layout;private int status;private LayoutParams params;private ImageView image;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);layout = (FrameLayout) findViewById(R.id.layout);// layout.setOnTouchListener(this);btn = (Button) findViewById(R.id.btn);btn.setDrawingCacheEnabled(true);btn.setOnTouchListener(this);params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);}@Overridepublic boolean onTouch(View view, MotionEvent me) {switch (me.getAction()) {case MotionEvent.ACTION_DOWN:status = START_DRAGGING;image = new ImageView(this);image.setImageBitmap(btn.getDrawingCache());layout.addView(image, params);break;case MotionEvent.ACTION_MOVE:if (status == START_DRAGGING) {image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);image.invalidate();}break;case MotionEvent.ACTION_UP:status = STOP_DRAGGING;Log.i("Drag", "Stopped Dragging");//layout.removeView(image);break;default:break;}return false;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.