Android image rotation, scaling, and cutting

Source: Internet
Author: User

I recently summarized the image processing methods in Android, as follows:

/*** Image inversion * @ Param IMG * @ return */Public bitmap toturn (Bitmap IMG) {matrix = new matrix (); matrix. postrotate (90);/* Flip 90 degrees */INT width = bitmap. getwidth (); int Height = bitmap. getheight (); IMG = bitmap. createbitmap (IMG, 0, 0, width, height, matrix, true); Return IMG ;} /*** image scaling ** @ Param bigimage * @ Param newwidth * @ Param newheight * @ return */Public bitmap tochange (Bitmap bigimage, int newwidth, int newheight) {// obtain the width and height of the image. Int width = bigimage. getwidth (); int Height = bigimage. getheight (); // The Matrix object matrix = new matrix () used to create an operation image; // calculate the scaling rate. The new size is equal to the original size float scalewidth = (float) newwidth)/width; float scaleheight = (float) newheight)/height; // scales the image action matrix. postscale (scalewidth, scaleheight); Bitmap bitmap = bitmap. createbitmap (bigimage, 0, 0, width, height, matrix, true); Return bitmap ;}

/*** Program cut image * @ 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 );}
/*** Image overlays * @ Param B * @ return */Public bitmap diejia (Bitmap B) {If (! B. ismutable () {// set the image to a transparent Background B = B. copy (bitmap. config. rgb_565, true); //} canvas = new canvas (B); bitmap lock = bitmapfactory. decoderesource (getresources (), R. drawable. ic_launcher); // overlay the new image B2 // note that the coordinates drawn at this time are relative to the image bcanvas. drawbitmap (lock, 0, 0, null); canvas. save (canvas. all_save_flag); canvas. restore (); lock. recycle (); lock = NULL; return B ;}

Picture center superposition:

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

/*** Method for obtaining images with reflections */public static bitmap createreflectionimagewithorigin (Bitmap bitmap) {final int reflectiongap = 4; int width = bitmap. getwidth (); int Height = bitmap. getheight (); 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 = 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 = 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 porterduduxfermode (mode. dst_in); // draw a rectangle using the paint with our linear gradient canvas. drawrect (0, height, width, bitmapwithreflection. getheight () + reflectiongap, paint); Return bitmapwithreflection ;}}

Convert relevant image parameters to form a new format of image data parameter display (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 * generate the watermark image * @ Param SRC the bitmap object you want proecss * @ Param watermark the water mark abve the SRC * @ return 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); // create a new bitmap canvas CV = new canvas (NEWB) with the same width as SRC; // draw SRC into cv. drawbitmap (SRC, 0, 0, null); // draw SRC at coordinates 0, 0 // draw watermark into cv. drawbitmap (watermark, W-ww + 5, H-Wh + 5, null); // Add the watermark to the bottom right corner of SRC // save all clip cv. save (canvas. all_save_flag); // save // store cv. restore (); // store 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();   }  

Phantom drag effect 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;/*** reference: 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, 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 ;}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.