[Android] uses the matrix matrix class to scale, rotate, contrast, and brightness the image

Source: Internet
Author: User

The previous article described Android taking photos, saved and displayed in the ImageView control, which continues to describe the Android image processing technology, including: by opening pictures in the album, using the Matrix to zoom, rotate, move, contrast, brightness, Saturation operation, we hope to help you.

one. Show Open picture

first, set the Activity_main.xml layout as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/container "android:layout_width=" Match_parent "android:layout_height= "Wrap_content" tools:context= "com.example.cangeimagetest.MainActivity" tools:ignore= "Mergerootframe" > &lt ; LinearLayout android:layout_width= "match_parent" android:layout_height= "wrap_content" android:orientation= "V Ertical "> <button android:id=" @+id/button1 "android:layout_width=" Match_parent "Android : layout_height= "wrap_content" android:text= "select Picture"/> <textview android:id= "@+id/textview1" a        Ndroid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:visibility= "Invisible" Android:text= "original display"/> <imageview android:id= "@+id/imageview1" android:layout_width= "wrap_content "Android:layout_gravity=" Center_horiZontal "android:layout_height=" wrap_content "/> <textview android:id=" @+id/textview2 "Androi D:layout_width= "Match_parent" android:layout_height= "wrap_content" android:visibility= "invisible" and roid:text= "changed picture"/> <imageview android:id= "@+id/imageview2" android:layout_gravity= "Center_horizo Ntal "android:layout_marginbottom=" 20DP "android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "/> </LinearLayout> <linearlayout android:layout_width=" Match_parent "Androi        d:layout_height= "wrap_content" android:orientation= "Horizontal" android:layout_alignparentbottom= "true" > <button android:id= "@+id/button2" android:layout_width= "Wrap_content" android:layout_height= "match _parent "android:layout_weight=" 1 "android:text=" Zoom Out "/> <button android:id=" @+id/button3 "Android:layout_Width= "Wrap_content" android:layout_height= "Match_parent" android:layout_weight= "1" android:text= "Zoom In" /> <button android:id= "@+id/button4" android:layout_width= "Wrap_content" android:layout _height= "Match_parent" android:layout_weight= "1" android:text= "rotate"/> <button android:id = "@+id/button5" android:layout_width= "wrap_content" android:layout_height= "Match_parent" Android:layo ut_weight= "1" android:text= "saturated"/> <button android:id= "@+id/button6" Android:layout_widt H= "Wrap_content" android:layout_height= "Match_parent" android:layout_weight= "1" android:text= "contrast"/&G    T </LinearLayout></RelativeLayout>

   

Private Button selectbn;private ImageView imageshow;private ImageView imagecreate;private TextView textview1;private TextView textview2;private Bitmap bmp;    Original picture @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);    SELECTBN = (Button) Findviewbyid (R.id.button1);    Imageshow = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);    Imagecreate = (ImageView) Findviewbyid (R.ID.IMAGEVIEW2);    Textview1 = (TextView) Findviewbyid (R.ID.TEXTVIEW1);        Textview2 = (TextView) Findviewbyid (R.ID.TEXTVIEW2); Select Picture Selectbn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent inte    NT = new Intent (Intent.action_pick, Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);    Startactivityforresult (Intent, 0);    }    }); if (savedinstancestate = = null) {Getfragmentmanager (). BeginTransaction (). Add (R.id.container, new P LaceHolderfragment ()). commit (); }}//shows two pictures protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (     Requestcode, ResultCode, data); if (RESULTCODE==RESULT_OK) {showphotobyimageview (data);          Show photo Createphotobyimageview (); Create picture}}

    and then call the custom function implementation to display the picture:

The custom function displays the open photo in ImageView1 public void Showphotobyimageview (Intent data) {Uri Imagefileuri = Data.getdata ();D Isplaymetrics dm = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); int width =    Dm.widthpixels;  Phone screen horizontal Resolution int height = Dm.heightpixels; Phone screen vertical resolution log.v ("height", "+height"); LOG.V ("width", "+width"); try {//Load up the image ' s dimensions not the image itselfbitmapfactory.options Bmpfactoryoption s = new bitmapfactory.options (); bmpfactoryoptions.injustdecodebounds = True;bmp = Bitmapfactory.decodestream ( Getcontentresolver (). Openinputstream (Imagefileuri), NULL, bmpfactoryoptions); int heightratio = (int) Math.ceil ( bmpfactoryoptions.outheight/(float) height), int widthRatio = (int) Math.ceil (bmpfactoryoptions.outwidth/(float) width); LOG.V ("Bmpheight", "+bmpfactoryoptions.outheight"); LOG.V ("Bmpheight", "" "+bmpfactoryoptions.outwidth); if (heightratio>1&&widthratio>1) {if (heightRatio >widthratio) {bmpfactoryoptions.insamplesize = heightratio*2;} ELSE {bmpfactoryoptions.insamplesize = WIDTHRATIO*2;}}              Image true Decoding bmpfactoryoptions.injustdecodebounds = false;      BMP = Bitmapfactory.decodestream (Getcontentresolver (). Openinputstream (Imagefileuri), NULL, bmpfactoryoptions); Imageshow.setimagebitmap (BMP); Show the cropped photo textview1.setvisibility (view.visible);} catch (FileNotFoundException e) {e.printstacktrace ();}} Create a second picture and show public void Createphotobyimageview () {try {Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.geth    Eight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); The canvas incoming bitmap is used to draw the paint paint = new paint ();    Paint brushes Change color contrast properties such as Canvas.drawbitmap (BMP, 0, 0, paint);    Error: No picture because the parameter BMP is written createbmp imagecreate.setimagebitmap (createbmp); Textview2.setvisibility (view.visible);} catch (Exception e) {e.printstacktrace ();}}

The displayed effect is shown in the graph called Lena (Lenna), which is a sample diagram that is often used in image processing.

two. Matrix Operation

The image is then processed through the matrix and a click event is added to the OnCreate function:

//Shrink Picture button Button2= (Button) Findviewbyid (R.id.button2); Button2.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {smallpicture ();}});    /Enlarge Picture button button3= (button) Findviewbyid (R.id.button3);   Button3.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {BigPicture ();}}); Rotate Picture button button4= (button) Findviewbyid (r.id.button4); Button4.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {turnpicture ();}}); /Image Saturation Change button button5= (button) Findviewbyid (R.ID.BUTTON5); Button5.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {saturationpicture ();}}); /Picture Contrast change Button button6= (Button) Findviewbyid (R.ID.BUTTON6); Button6.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {contrastpicture ();}}); 

    Finally, each operation is implemented by customizing the function, the code is as follows:

Shrink picture private void smallpicture () {Matrix matrix = new Matrix ();//Zoom Interval 0.5-1.0if (smallbig>0.5f) smallbig= smallbig-0.1f;elsesmallbig=0.5f;//x y-coordinate simultaneous scaling Matrix.setscale (Smallbig,smallbig,bmp.getwidth ()/2,bmp.getHeight ()/2 ); Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.getheight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); The canvas incoming bitmap is used to draw the paint paint = new paint ();    Paint brushes Change color contrast properties such as Canvas.drawbitmap (BMP, Matrix, paint);    Imagecreate.setbackgroundcolor (color.red);    Imagecreate.setimagebitmap (createbmp);    Textview2.setvisibility (view.visible); }//Enlarge the image private void BigPicture () {Matrix matrix = new Matrix ();//Zoom Interval 0.5-1.0if (smallbig<1.5f) smallbig=smallbig+ 0.1f;elsesmallbig=1.5f;//x y-coordinate simultaneously scales Matrix.setscale (Smallbig,smallbig,bmp.getwidth ()/2,bmp.getheight ()/2); Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.getheight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); Paint paint = new paint (); Canvas.drawbitmap (BMP, Matrix, paint); imagEcreate.setbackgroundcolor (color.red); Imagecreate.setimagebitmap (createbmp); Textview2.setvisibility ( view.visible);} Rotate picture private void turnpicture () {Matrix matrix = new Matrix (); turnrotate=turnrotate+15;//Select Angle Rao (0,0) point Select positive number clockwise negative counterclockwise center rotation Matrix.setrotate (Turnrotate,bmp.getwidth ()/2,bmp.getheight ()/2); Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.getheight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); Paint paint = new paint (); Canvas.drawbitmap (BMP, Matrix, paint); Imagecreate.setbackgroundcolor (color.red); Imagecreate.setimagebitmap ( createbmp); textview2.setvisibility (view.visible);} Change image saturation private void saturationpicture () {//Set saturation 0 indicates a grayscale image greater than 1 saturation increased 0-1 saturation decreased colormatrix cm = new ColorMatrix (); Cm.setsaturation (saturation); Paint paint = new paint (); Paint.setcolorfilter (new Colormatrixcolorfilter (cm));//Display picture matrix matrix = new Matrix (); Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.getheight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); CanvAs.drawbitmap (BMP, Matrix, paint); Imagecreate.setimagebitmap (createbmp); textview2.setvisibility (view.visible); Saturation=saturation+0.1f;if (saturation>=1.5f) {saturation=0f;}}  Set picture contrast private void contrastpicture () {ColorMatrix cm = new ColorMatrix (); Float brightness =-25;        brightness float contrast = 2; Contrast Cm.set (new float[] {contrast, 0, 0, 0, brightness,0, contrast, 0, 0, brightness,0, 0, contrast, 0, brightness,0, 0, 0 , contrast, 0}); Paint paint = new paint (); Paint.setcolorfilter (new Colormatrixcolorfilter (cm));//Display picture matrix matrix = new Matrix (); Bitmap createbmp = Bitmap.createbitmap (Bmp.getwidth (), Bmp.getheight (), Bmp.getconfig ()); Canvas canvas = new canvas (createbmp); Canvas.drawbitmap (BMP, Matrix, paint); Imagecreate.setimagebitmap (createbmp); Textview2.setvisibility (View.VISIBLE );}

also the custom variables are as follows:

Picture transform parameters private float smallbig=1.0f;   scale private int turnrotate=0;       Rotation degree private float saturation=0f;    Saturation level

It runs as shown in the results:



It should be pointed out that: The project only describes the process of processing, and does not take into account many factors, such as: Some image display may exceed the screen, not loaded image click processing button error, the screen switch led to not show the picture, the bottom button may be obscured, the image enlarged canvas has not changed, Because it's better to think of showing a changed picture, the project is just a contrast. Image zoom Mobile touch screen transform better, next story.
XML Layout Recommendation: http://www.apkbus.com/forum.php?mod=viewthread&tid=44949
Resolve canvas to enlarge with Image: Http://www.eoeandroid.com/thread-3162-1-1.html

three. The Matrix processing principle

images can be processed in Android using the Matrix and ColorMatrix.
1.Matrix
image space transformations, including rotation, clipping, zooming, or moving. Each number in the matrix class is applied to one of the 3 coordinate x\y\z of each point on the image.
the following code sets the value through Setvalues. 1,0,0) represents the x-coordinate conversion x=1x+0y+0z, the same y=0x+1y+0z,z=0x+0y+1z. The matrix does not make any transformations. if the first line is changed to (. 5f,0,0), the image is compressed on the x-axis 50%. Move to see Settranslate () function.

Matrix matrix = new Matrix (); Matrix.setvalues (new float[] {        1, 0, 0,        0, 1, 0,        0, 0, 1});

2.ColorMatrix
You can use the matrix method when drawing on a canvas object, or you can use ColorMatrix to change the paint (brush) object that is drawn on the canvas object. Each pixel is composed of rgba values when processing pixels in the image (Red Green Blue Alpha). Specific method Recommended Blog:http://www.cnblogs.com/leon19870907/articles/1978065.html
Finally, I hope this article is helpful to everyone, especially Android beginners. This article is about Android using the matrix processing pictures of the basic article, if there is insufficient or wrong place, please forgive ~ reference "Advanced programming for Android Multimedia development: Shawn Van Every"
:
(By:eastmount 2014-10-26 Night 2 o ' http://blog.csdn.net/eastmount)

[Android] uses the matrix matrix class to scale, rotate, contrast, and brightness the image

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.