Image processing Class Bitmaputils can be used in Android

Source: Internet
Author: User

Android in the actual development of a lot of time to deal with the image, the summary of the Bitmaputils class contains a few features:

1.Android Image Reflection,

2.Android image blur processing,

3.Android Picture fillet processing,

4. The picture rotates at a certain angle along the y axis,

5.Android add a border to the picture.

6. Convert view to bitmap

7. compress the large picture two times

8. Compress image to get thumbnail image

9. Get thumbnail images of local file videos

10. Get thumbnail images of local files


The next step is to go directly to the code, which has some explanation in the code .

You can use it directly.

</pre><pre name= "code" class= "java" >/* * @Title: Bitmaputils.java * @Description:todo< Please describe what this file is for > * @author: XJP * @data: September 18, 2014 Morning 10:10:30 * @version: V1.0 */package com.mktech.bitmaputils;import Android.annota tion. Suppresslint;import Android.annotation.targetapi;import Android.content.context;import Android.content.res.resources;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.bitmapshader;import Android.graphics.camera;import Android.graphics.canvas;import Android.graphics.lineargradient;import Android.graphics.matrix;import Android.graphics.paint;import Android.graphics.porterduffxfermode;import Android.graphics.bitmap.config;import Android.graphics.Rect;import Android.graphics.rectf;import Android.graphics.shader;import Android.graphics.shader.tilemode;import Android.media.thumbnailutils;import Android.os.build;import Android.renderscript.allocation;import Android.renderscript.element;import Android.renderscript. Renderscript;import Android.renderscript.scriptintrinsicblur;import Android.util.log;import Android.view.View; Import android.view.view.measurespec;/** * todo< Please describe what this class is for > * * @author XJP * @data: September 18, 2014 Morning 10:10:30 * @ver    sion:v1.0 */public class Bitmaputils {private static final String TAG = "Bitmaputils"; /** * todo< convert control to BITMAP type > * * @throw * @return Bitmap * @param paramview *: Conversion required Control */public static Bitmap Convertviewtobitmap (View paramview) {paramview.measure (MeasureS        Pec.makemeasurespec (0, measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified));        Paramview.layout (0, 0, paramview.getmeasuredwidth (), Paramview.getmeasuredheight ());        Paramview.builddrawingcache ();    return Paramview.getdrawingcache (); }/** * todo< Create reflection Image > * * @throw * @return Bitmap * @param srcbitmap * sourcePicture of Bitmap * @param reflectionheight * Image Reflection Height */public static Bitmap Createreflectedbitmap (BITM AP Srcbitmap, int reflectionheight) {if (null = = Srcbitmap) {log.e (TAG, "The Srcbitmap is n            Ull ");        return null;        }//The gap between the reflection bitmap and original bitmap.        Final int reflection_gap = 0;        int srcwidth = Srcbitmap.getwidth ();        int srcheight = Srcbitmap.getheight ();            if (0 = = Srcwidth | | srcheight = 0) {log.e (TAG, "The Srcbitmap is null");        return null;        }//The matrix matrix matrix = new Matrix ();        Matrix.prescale (1,-1);            try {//The reflection bitmap, width is same with original ' s, height is//half of original ' s. Bitmap Reflectionbitmap = Bitmap.createbitmap (srcbitmap, 0, Srcheight-reflectionheight, SRCWI DTH, Reflectionheight, Matrix, False);                if (null = = Reflectionbitmap) {log.e (TAG, "Create The Reflectionbitmap is failed");            return null;            }//Create the bitmap which contains original and reflection bitmap. Bitmap bitmapwithreflection = Bitmap.createbitmap (srcwidth, Srcheight + reflectionheight, Bitmap.config .            argb_8888);            if (null = = bitmapwithreflection) {return null;            }//Prepare the canvas to draw stuff.            Canvas canvas = new canvas (bitmapwithreflection);            Draw the original bitmap.            Canvas.drawbitmap (srcbitmap, 0, 0, NULL);            Draw the reflection bitmap.            Canvas.drawbitmap (reflectionbitmap, 0, srcheight + reflection_gap, NULL);            Paint paint = new paint ();            Paint.setantialias (TRUE); LinearGradient shader = new LinearGradient (0, srcheight, 0, BitmapwithreflectiOn.getheight () + Reflection_gap, 0x70ffffff, 0X00FFFFFF, Tilemode.mirror);            Paint.setshader (shader);            Paint.setxfermode (New Porterduffxfermode (Android.graphics.PorterDuff.Mode.DST_IN));            Canvas.save ();            Draw the linear shader.            Canvas.drawrect (0, Srcheight, Srcwidth, bitmapwithreflection.getheight () + reflection_gap, paint); if (Reflectionbitmap! = null &&!reflectionbitmap.isrecycled ()) {reflectionbitmap.recycle (                );            Reflectionbitmap = null;            } canvas.restore ();        return bitmapwithreflection;        } catch (Exception e) {e.printstacktrace ();        } log.e (TAG, "Create The Reflectionbitmap is failed");    return null; }/** * todo< picture fillet processing > * * @throw * @return Bitmap * @param srcbitmap * source Image Bitm          AP * @param ret *  The degree of the fillet */public static Bitmap Getroundimage (Bitmap srcbitmap, float ret) {if (null = = Srcbitmap) {            LOG.E (TAG, "The Srcbitmap is null");        return null;        } int bitwidth = Srcbitmap.getwidth ();        int bithight = Srcbitmap.getheight ();        Bitmapshader Bitmapshader = new Bitmapshader (Srcbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);        Paint paint = new paint ();        Paint.setantialias (TRUE);        Paint.setshader (Bitmapshader);        RECTF RECTF = new RECTF (0, 0, bitwidth, bithight);        Bitmap Outbitmap = Bitmap.createbitmap (Bitwidth, Bithight, config.argb_8888);        Canvas canvas = new canvas (OUTBITMAP);        Canvas.drawroundrect (RECTF, ret, ret, paint);        Canvas.save ();        Canvas.restore ();    return outbitmap; }/** * todo< picture is rotated along the Y axis at a certain angle > * * @throw * @return Bitmap * @param srcbitmap * source Map Piece of bitmap * @param reflectiOnheight * Image Reflection Height * @param rotate * Picture rotation angle */public static Bitmap Skewimage (Bi TMap Srcbitmap, float rotate, int reflectionheight) {if (null = = Srcbitmap) {log.e (TAG, "th            E Srcbitmap is null ");        return null;        } Bitmap Reflectebitmap = Createreflectedbitmap (Srcbitmap, reflectionheight);            if (null = = Reflectebitmap) {log.e (TAG, "failed to Createreflectedbitmap");        return null;        } int wbitmap = Reflectebitmap.getwidth ();        int hbitmap = Reflectebitmap.getheight ();        float ScaleWidth = ((float)/wbitmap;        float ScaleHeight = ((float))/hbitmap;        Matrix matrix = new Matrix ();        Matrix.postscale (ScaleWidth, ScaleHeight);        Reflectebitmap = Bitmap.createbitmap (reflectebitmap, 0, 0, Wbitmap, Hbitmap, Matrix, True);        Camera Localcamera = new camera ();     Localcamera.save ();   Matrix Localmatrix = new Matrix ();        Localcamera.rotatey (rotate);        Localcamera.getmatrix (Localmatrix);        Localcamera.restore ();        Localmatrix.pretranslate (-reflectebitmap.getwidth () >> 1,-reflectebitmap.getheight () >> 1); Bitmap localBitmap2 = Bitmap.createbitmap (reflectebitmap, 0, 0, reflectebitmap.getwidth (), Reflectebi        Tmap.getheight (), Localmatrix, true); Bitmap localBitmap3 = Bitmap.createbitmap (Localbitmap2.getwidth (), Localbitmap2.getheight (), Bitmap.config.        argb_8888);        Canvas Localcanvas = new canvas (LOCALBITMAP3);        Paint Localpaint = new paint ();        Localpaint.setantialias (TRUE);        Localpaint.setfilterbitmap (TRUE);        Localcanvas.drawbitmap (LOCALBITMAP2, 0.0F, 0.0F, Localpaint);            if (null! = Reflectebitmap &&!reflectebitmap.isrecycled ()) {reflectebitmap.recycle ();        Reflectebitmap = null; } if (Null! = LOCALBITMAP2 &&!localbitmap2.isrecycled ()) {localbitmap2.recycle ();        LOCALBITMAP2 = null;        } localcanvas.save ();        Localcanvas.restore ();    return LOCALBITMAP3; /** * todo< image Blur processing > * * @throw * @return Bitmap * @param Bitmap * Source image *            @param radius * The radius of the blur supported range 0 < radius <= * @param context * Context */@TargetApi (build.version_codes. JELLY_BEAN_MR1) @SuppressLint ("Newapi") public static Bitmap Blurbitmap (Bitmap Bitmap, float radius, context context ) {//Let ' s create a empty bitmap with the same size of the bitmap we want//to blur bitmap Outbit        Map = Bitmap.createbitmap (Bitmap.getwidth (), Bitmap.getheight (), config.argb_8888);        Instantiate a new renderscript renderscript rs = renderscript.create (context); Create an intrinsic Blur ScRipt using the renderscript scriptintrinsicblur Blurscript = scriptintrinsicblur.create (RS, Element.        U8_4 (RS)); Create the Allocations (in/out) with the Renderscript and the in/out//bitmaps Allocation Allin = Alloca        Tion.createfrombitmap (rs, bitmap);        Allocation Allout = Allocation.createfrombitmap (RS, outbitmap);        Set the radius of the blur if (Radius >) {radius = 25.0f;        } else if (radius <= 0) {radius = 1.0f;        } blurscript.setradius (RADIUS);        Perform the Renderscript blurscript.setinput (Allin);        Blurscript.foreach (Allout);        Copy the final bitmap created by the-Allocation to the Outbitmap Allout.copyto (OUTBITMAP);        Recycle the original bitmap bitmap.recycle ();        bitmap = null;        After finishing everything, we destroy the Renderscript.        Rs.destroy ();    return outbitmap;     }    /*** todo< Add a border of the specified color to the picture > * * @param srcbitmap * Original picture * @param borderWidth * Border Width  * @param color * @return * */public static Bitmap Addframebitmap (Bitmap srcbitmap, int borderWidth, int color) {if (Srcbitmap = = null) {LOG.E (TAG, "the Srcbitmap or Borderbi            TMap is null ");        return null;        } int newwidth = Srcbitmap.getwidth () + borderWidth;        int newheight = srcbitmap.getheight () + borderWidth;        Bitmap Outbitmap = Bitmap.createbitmap (Newwidth, Newheight, config.argb_8888);        Canvas canvas = new canvas (OUTBITMAP);        Rect rec = canvas.getclipbounds ();        rec.bottom--;        rec.right--;        Paint paint = new paint ();        Sets the border color paint.setcolor (color);        Paint.setstyle (Paint.Style.STROKE);        Set Border width paint.setstrokewidth (borderWidth);        Canvas.drawrect (REC, paint); Canvas.drawBitmap (Srcbitmap, BORDERWIDTH/2, BORDERWIDTH/2, NULL);        Canvas.save (Canvas.all_save_flag);        Canvas.restore ();            if (Srcbitmap! = null &&!srcbitmap.isrecycled ()) {srcbitmap.recycle ();        Srcbitmap = null;    } return Outbitmap; } public static Bitmap Decodesampledbitmapfromresource (Resources res, int resId, int reqwidth, int reqheight        {Final Bitmapfactory.options Options = new Bitmapfactory.options ();        Set the Injustdecodebounds property to true first, decoding avoids memory allocation options.injustdecodebounds = TRUE;        Pass the picture to the selector Bitmapfactory.decoderesource (res, resId, options);        Compression of the specified proportions of the picture options.insamplesize = calculateinsamplesize (options, Reqwidth, reqheight);        After the picture processing, then the memory allocation, to avoid the occurrence of memory leakage options.injustdecodebounds = false;    Return Bitmapfactory.decoderesource (res, resId, options); }//Calculate the compressed proportions of the picture public static int Calculateinsamplesize (bitmapfactOry. Options option, int reqwidth, int reqheight) {//Raw height and width of image final int height        = Option.outheight;        Final int width = option.outwidth;        int insamplesize = 1;                    if (Height > Reqheight | | width > reqwidth) {final int heightratio = Math.Round ((float) Height            /(float) reqheight);            Final int widthRatio = Math.Round ((float) width/(float) reqwidth); Select a ratio that is smaller in length and width. Become compression ratio insamplesize = HeightRatio < WidthRatio?

Heightratio:widthratio; } return insamplesize; }/** * Creates a centered bitmap of the desired size. * * @param source * Original Bitmap source * @param width * Targeted width * @pa Ram Height * Targeted Height * * public static Bitmap Thumbnail (Bitmap BM, int reqwidth, int reqheigh T) {Bitmap BMP = null; BMP = Thumbnailutils.extractthumbnail (BM, reqwidth, reqheight); return BMP; }/** * Creates a centered bitmap of the desired size. * * @param source * Original Bitmap source * @param width * Targeted width * @pa Ram Height * Targeted Height * @param options * options used during thumbnail extraction */public static Bitmap Thumbnail (Bitmap BM, int reqwidth, int reqheight, int options) {Bitmap BMP = NULL; BMP = Thumbnailutils.extractthumbnail (BM, ReqwidTh, reqheight, options); return BMP; }//create thumbnails of file videos/** * Create a video thumbnail for a video. May return NULL if the video was * corrupt or the format is not supported. * * @param FilePath * The path of the video file * @param kind * Could be mini_kind or M Icro_kind */public static Bitmap Createvideothumbnail (String filePath, int KIND) {return thumbnailutils.cr Eatevideothumbnail (FilePath, kind); }//Create a thumbnail image of the file/** * This method first examines if the thumbnail embedded in EXIF are bigger * than our Targe T size. If not, then it's ll create a thumbnail from original * image. Due to efficiency consideration, we want to let Mediathumbrequest * Avoid calling this method twice for both kinds, so It is requests for * Micro_kind and set SaveImage to True. This method is always returns a * "square thumbnail" for micro_kind thumbnail. * * @param FilePath * The path of Image file * @param kind * could be Images.Thumbnails.MINI_KIND or * images.thumbnails. Mini_kind * @return Bitmap, or null on failures * @hide This method was only used by media framework and media prov Ider * internally. */public static Bitmap Createimagethumbnail (String filePath, int kind) {return thumbnailutils.createimagethumb Nail (filePath, kind); }}





The above code is validated to be used directly.

Share .

End.



Image processing Class Bitmaputils can be used in Android

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.