[Android] Using Matrix to scale, rotate, contrast, and brightness Images

Source: Internet
Author: User

[Android] Using Matrix to scale, rotate, contrast, and brightness Images

The previous article describes how to take photos, save and display images in the ImageView control of Android. This article continues with the Android image processing technology. The main operations include opening pictures in the album, use Matrix to scale, rotate, move, contrast, brightness, and saturation the image.

1. Show open Images

First, set the activity_main.xml layout as follows:

         
          
       
       
       
       
       
          
          
           
           
           
           
       
  
 

Then, add the following code to the public class MainActivity extends Activity function in Mainctivity. java:

Private Button selectBn; private ImageView imageShow; private ImageView imageCreate; private TextView textview1; private TextView textview2; private Bitmap bmp; // original image @ 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 the image selectBn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {Intent intent = 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 PlaceholderFragment ()). commit () ;}// display two images: protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); if (resultCode = RESULT_ OK) {ShowPhotoByImageView (data); // display the photo CreatePhotoByImageView (); // create an image }}

Call the custom function to display the image:

// The custom function displays the opened image in ImageView1. public void ShowPhotoByImageView (Intent data) {Uri imageFileUri = data. getData (); DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); int width = dm. widthPixels; // The horizontal resolution of the phone screen. int height = dm. heightPixels; // Log of the vertical resolution of the mobile phone screen. v ("height", "" + height); Log. v ("width", "" + width); try {// Load up the image's dimensions not the image itselfBitmapFactory. options BMP factoryoptions = new BitmapFactory. options (); BMP factoryoptions. inJustDecodeBounds = true; bmp = BitmapFactory. decodeStream (getContentResolver (). openInputStream (imageFileUri), null, BMP factoryoptions); int heightRatio = (int) Math. ceil (BMP factoryoptions. outHeight/(float) height); int widthRatio = (int) Math. ceil (BMP factoryoptions. outWidth/(float) width); Log. v ("bmpheight", "" + BMP factoryoptions. outHeight); Log. v ("bmpheight", "" + BMP factoryoptions. outWidth); if (heightRatio> 1 & widthRatio> 1) {if (heightRatio> widthRatio) {BMP factoryoptions. inSampleSize = heightRatio * 2;} else {BMP factoryoptions. inSampleSize = widthRatio * 2 ;}// the image is actually decoded by BMP factoryoptions. inJustDecodeBounds = false; bmp = BitmapFactory. decodeStream (getContentResolver (). openInputStream (imageFileUri), null, BMP factoryoptions); imageShow. setImageBitmap (bmp); // display textview1.setVisibility (View. VISIBLE);} catch (FileNotFoundException e) {e. printStackTrace () ;}// create the second image and display the public void CreatePhotoByImageView () {try {Bitmap createBmp = Bitmap. createBitmap (bmp. getWidth (), bmp. getHeight (), bmp. getConfig (); Canvas canvas = new Canvas (createBmp); // pass in a canvas bitmap for painting Paint = new paint (); // click it to change the color contrast and other attributes Canvas. drawBitmap (bmp, 0, 0, paint); // error: no image. Because the bmp parameter is written as createBmp imageCreate. setImageBitmap (createBmp); textview2.setVisibility (View. VISIBLE);} catch (Exception e) {e. printStackTrace ();}}

Shows the displayed effect,This figure is called Lenna. It is often used in image processing.

Ii. Matrix Operations

Then, use Matrix to process the image and add a click event to the onCreate function:

// Narrow down the image Button button2 = (Button) findViewById (R. id. button2); button2.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {SmallPicture () ;}}); // enlarge the image Button button3 = (Button) findViewById (R. id. button3); button3.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {BigPicture () ;}}); // rotate the image Button button4 = (Button) findViewById (R. id. button4); button4.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {TurnPicture () ;}}); // Button button5 = (Button) findViewById (R. id. button5); button5.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {SaturationPicture () ;}}); // The image contrast changes to the Button button6 = (Button) findViewById (R. id. button6); button6.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {ContrastPicture ();}});

The code for customizing the function operations is as follows:

// Zoom out the image private void SmallPicture () {Matrix matrix = new Matrix (); // zoom range 0.5-1.0if (smallbig> 0.5f) smallbig = smallbig-0.1f; elsesmallbig = 0.5f; // scale the matrix at the same time by x y coordinate. setScale (smallbig, smallbig, bmp. getWidth ()/2, bmp. getHeight ()/2); Bitmap createBmp = Bitmap. createBitmap (bmp. getWidth (), bmp. getHeight (), bmp. getConfig (); Canvas canvas = new Canvas (createBmp); // pass in a canvas bitmap for painting Paint = new paint (); // click it to change the color contrast and other attributes 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 (); // The scaling range is 0.5-1.0if (smallbig <1.5f) smallbig = smallbig + 0.1f; elsesmallbig = 1.5f; // The x y coordinate scales the matrix simultaneously. 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 the image private void TurnPicture () {Matrix matrix = new Matrix (); turnRotate = turnRotate + 15; // select the angle Rao (0, 0) point select positive number clockwise negative number counter-clockwise center rotating 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 the image saturation private void SaturationPicture () {// set the saturation 0 to indicate that the grayscale image is greater than 1, the saturation increases by 0-1, and the ColorMatrix cm = new ColorMatrix (); cm. setSaturation (saturation); Paint paint = new Paint (); paint. setColorFilter (new ColorMatrixColorFilter (cm); // display the image 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 ;}// sets the Image Contrast private void ContrastPicture () {ColorMatrix cm = new ColorMatrix (); float brightness =-25; // 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 the image 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 );}

The custom variables are as follows:

// Image conversion parameter private float smallbig = 1.0f; // scaling ratio private int turnRotate = 0; // Rotation Degree private float saturation = 0f; // saturation

The running result is shown in:



It should be pointed out that this project only describes the processing process and does not take many factors into account. For example, some images may be displayed beyond the screen and an error is reported if the image is not loaded and the processing button is clicked, the horizontal and vertical screen switching causes no image to be displayed, and the bottom button may be blocked. The image zoom-in canvas does not change, because the project is only compared to display a changed image. image Scaling and moving touch screen transformation are better.
XML layout recommendations: http://www.apkbus.com/forum.php? Mod = viewthread & tid = 44949.
Solve the canvas to zoom in with the image: http://www.eoeandroid.com/thread-3162-1-1.html

Iii. Principles of Matrix Processing

In Android, images can be processed through Matrix and ColorMatrix.
1. Matrix
Image space transformation, including rotation, cropping, scaling, or moving. Each number in the Matrix class will be applied to one of the three coordinates x \ y \ z of each point on the image.
The following code uses setValues to set the value. (, 0) indicates x coordinate transformation x = 1x + 0y + 0z, and y = 0x + 1y + 0z, z = 0x + 0y + 1z. this matrix does not undergo any transformation.If the first line is changed to (. 5f, 50%), the image will be compressed by on the X axis. For more information, 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 or ColorMatrix to change the painting objects drawn on a Canvas object. each pixel is composed of the RGBA value (Red Green Blue Alpha ). specific method recommended blog: http://www.cnblogs.com/leon19870907/articles/1978065.html
Finally, I hope this article will be helpful to you, especially for beginners of Android. This article is a basic article about how Android uses Matrix to process images. If there are any deficiencies or errors, please forgive me ~ References 《Advanced Programming for Android multimedia development: Shawn Van Every"
:
(By: Eastmount http://blog.csdn.net/eastmount)

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.